RHEL BasedRocky Linux

How To Install Nginx on Rocky Linux 10

Install Nginx on Rocky Linux 10

Nginx stands as one of the most powerful and efficient web servers available today, serving millions of websites worldwide with exceptional performance and reliability. When combined with Rocky Linux 10’s enterprise-grade stability, this combination creates an ideal foundation for production web environments. This comprehensive guide will walk you through the complete process of installing and configuring Nginx on Rocky Linux 10, from initial setup to advanced optimization techniques.

Rocky Linux 10 represents the latest evolution of enterprise-class Linux distributions, offering enhanced security features, improved performance, and long-term support that makes it perfect for hosting critical web applications. Nginx’s event-driven architecture provides superior performance compared to traditional web servers, handling thousands of concurrent connections with minimal resource consumption. Whether you’re deploying a simple website or a complex web application infrastructure, this guide ensures you’ll have a robust, secure, and optimized web server environment.

Understanding Nginx and Rocky Linux 10

Nginx (pronounced “engine-x”) revolutionized web server technology with its asynchronous, event-driven architecture that efficiently handles high-traffic scenarios. Unlike traditional web servers that create new processes or threads for each connection, Nginx uses a master process with multiple worker processes, dramatically reducing memory overhead and improving scalability. This design makes it exceptionally well-suited for serving static content, acting as a reverse proxy, and load balancing across multiple backend servers.

Rocky Linux 10 builds upon the solid foundation of enterprise Linux distributions, providing a stable, secure platform that’s fully compatible with Red Hat Enterprise Linux. The distribution includes updated package repositories, enhanced security features, and improved container support. For web server deployments, Rocky Linux 10 offers several advantages: robust firewall management with firewalld, SELinux integration for enhanced security, and comprehensive package management through DNF.

The combination of Nginx and Rocky Linux 10 creates a powerful platform capable of handling enterprise workloads while maintaining excellent performance characteristics. This pairing is particularly popular in cloud environments, containerized deployments, and high-availability web services where reliability and performance are paramount.

Prerequisites and System Preparation

System Requirements

Before beginning the Nginx installation, ensure your Rocky Linux 10 system meets the minimum hardware requirements. A basic Nginx installation requires at least 512MB of RAM, though 1GB or more is recommended for production environments. CPU requirements are minimal, but having multiple cores allows Nginx to leverage its multi-process architecture effectively.

Verify your Rocky Linux 10 installation is complete and properly configured. Check the system version using cat /etc/rocky-release to confirm you’re running Rocky Linux 10. The system should have a stable network connection and properly configured hostname resolution.

User Privileges

Root access or sudo privileges are essential for installing packages and configuring system services. If you’re not logged in as root, ensure your user account has sudo privileges. Create a dedicated user account for web administration if needed, following the principle of least privilege for enhanced security.

Verify sudo access by running sudo whoami, which should return “root” if properly configured. This access level is necessary for installing packages, modifying system configurations, and managing services throughout the installation process.

Network Configuration

Confirm internet connectivity by testing DNS resolution with nslookup google.com or ping -c 4 8.8.8.8. Proper network connectivity is crucial for downloading packages and updates during the installation process.

Check that the system’s firewall configuration allows necessary outbound connections for package downloads. While we’ll configure inbound web traffic rules later, ensure the system can reach external package repositories for the initial installation.

Initial System Updates

Update the system package repositories and installed packages to ensure you’re working with the latest security patches and software versions. Run sudo dnf update -y to download and install all available updates. This process may take several minutes depending on your internet connection and the number of available updates.

If kernel updates are installed during this process, reboot the system with sudo reboot to ensure the new kernel is active. After rebooting, verify the system is running the updated kernel with uname -r.

Step-by-Step Nginx Installation Process

Step 1: Update System Packages

Begin by ensuring your Rocky Linux 10 system has the latest package information and security updates. Execute the following command to refresh package repositories and install available updates:

sudo dnf update -y

This command downloads and installs all available package updates, including security patches and bug fixes. The process typically takes 2-5 minutes depending on your internet connection and the number of updates available. Monitor the output for any error messages that might indicate repository connectivity issues.

Step 2: Install Nginx Using DNF

Rocky Linux 10 includes Nginx in its default package repositories, making installation straightforward. Install Nginx and its dependencies using the DNF package manager:

sudo dnf install nginx -y

The installation process automatically resolves dependencies and downloads approximately 1-3MB of packages. DNF will display the package information and dependency list before proceeding with the installation. Once completed, verify the installation by checking the Nginx version:

nginx -v

This command should display the installed Nginx version, confirming successful installation. The version output typically shows both the Nginx version number and compilation date.

Step 3: Enable and Start Nginx Service

Configure Nginx to start automatically at boot time and start the service immediately. Use systemctl to manage the Nginx service:

sudo systemctl enable --now nginx

This combined command both enables the service for automatic startup and starts it immediately. Alternatively, you can run these commands separately:

sudo systemctl enable nginx
sudo systemctl start nginx

Verify the service status to ensure Nginx is running correctly:

sudo systemctl status nginx

The output should show “Active: active (running)” in green text, indicating the service is operational. If the service fails to start, check the error logs for troubleshooting information.

Step 4: Configure Firewall for Web Traffic

Rocky Linux 10 uses firewalld for firewall management, which blocks web traffic by default. Open the necessary ports to allow HTTP and HTTPS traffic:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

The first command opens port 80 for HTTP traffic, the second opens port 443 for HTTPS traffic, and the third reloads the firewall configuration to apply the changes. Verify the firewall configuration:

sudo firewall-cmd --permanent --list-all

The output should include “http” and “https” in the services list, confirming web traffic is allowed through the firewall.

Initial Configuration and Testing

Testing the Installation

Verify Nginx is properly serving web pages by accessing the default welcome page. Open a web browser and navigate to your server’s IP address:

http://your-server-ip

You should see the default Nginx welcome page displaying “Welcome to nginx!” This confirms the web server is responding to HTTP requests correctly.

For command-line testing, use curl to verify local connectivity:

curl http://localhost
curl http://127.0.0.1

Both commands should return the HTML content of the default Nginx welcome page. If you encounter connection refused errors, verify the Nginx service is running and the firewall is properly configured.

Understanding Nginx Directory Structure

Familiarize yourself with Nginx’s file system layout on Rocky Linux 10. The main configuration file is located at /etc/nginx/nginx.conf, which contains global settings and includes additional configuration files from /etc/nginx/conf.d/.

The default document root directory is /usr/share/nginx/html/, containing the default welcome page and error pages. Log files are stored in /var/log/nginx/, with separate files for access logs (access.log) and error logs (error.log).

Server block configurations for individual websites are typically stored in /etc/nginx/conf.d/ with .conf file extensions. This modular approach allows easy management of multiple websites on a single server.

Understanding this directory structure is crucial for effective Nginx administration, troubleshooting, and configuration management in production environments.

Basic Nginx Configuration

Editing the Main Configuration File

The primary Nginx configuration file /etc/nginx/nginx.conf contains global settings that affect the entire web server. Before making changes, create a backup copy:

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup

Open the configuration file with your preferred text editor:

sudo nano /etc/nginx/nginx.conf

Key configuration sections include the events block for connection handling, the http block for web server settings, and server blocks for individual websites. Adjust the worker_processes directive to match your server’s CPU cores for optimal performance.

The worker_connections setting within the events block determines how many simultaneous connections each worker process can handle. For most scenarios, the default value of 1024 is sufficient, but high-traffic sites may benefit from higher values.

Creating Your First Virtual Host

Virtual hosts (server blocks) allow hosting multiple websites on a single Nginx installation. Create a new configuration file for your website in the /etc/nginx/conf.d/ directory:

sudo nano /etc/nginx/conf.d/example.com.conf

Add the following basic server block configuration:

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

Create the document root directory and set appropriate permissions:

sudo mkdir -p /var/www/example.com/html
sudo chown -R nginx:nginx /var/www/example.com
sudo chmod -R 755 /var/www/example.com

Test the configuration syntax before applying changes:

sudo nginx -t

If the test passes, reload Nginx to apply the new configuration:

sudo systemctl reload nginx

Security Hardening and Best Practices

Basic Security Measures

Implementing security hardening measures protects your Nginx installation from common attacks and vulnerabilities. Hide the Nginx version information to prevent attackers from exploiting version-specific vulnerabilities:

server_tokens off;

Add this directive to the http block in /etc/nginx/nginx.conf or within individual server blocks. This prevents Nginx from displaying version information in HTTP headers and error pages.

Configure essential security headers to protect against common web vulnerabilities:

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Disable unnecessary HTTP methods that aren’t required for normal website operation:

if ($request_method !~ ^(GET|POST|HEAD)$) {
    return 444;
}

SELinux Considerations

Rocky Linux 10 includes SELinux enabled by default, which may interfere with Nginx operations if not properly configured. Check SELinux status:

getenforce

If SELinux is enforcing, configure appropriate contexts for web content directories:

sudo setsebool -P httpd_can_network_connect 1
sudo semanage fcontext -a -t httpd_exec_t "/etc/nginx/nginx.conf"
sudo restorecon -R /etc/nginx/
sudo restorecon -R /var/www/

These commands allow Nginx to network connections and ensure proper SELinux contexts for configuration and content files.

Advanced Configuration Topics

Performance Optimization

Optimize Nginx performance through strategic configuration adjustments. Configure worker processes to match your server’s CPU cores:

worker_processes auto;
worker_connections 1024;

Enable gzip compression to reduce bandwidth usage and improve page load times:

gzip on;
gzip_vary on;
gzip_min_length 1000;
gzip_comp_level 6;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/javascript
    application/xml+rss
    application/json;

Configure browser caching for static content to reduce server load:

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

Reverse Proxy Setup

Configure Nginx as a reverse proxy to distribute traffic across multiple backend servers. This setup improves scalability and provides load balancing capabilities:

upstream backend {
    server 127.0.0.1:8080;
    server 127.0.0.1:8081;
    server 127.0.0.1:8082;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

This configuration distributes incoming requests across three backend servers, providing automatic failover and load distribution.

Monitoring and Maintenance

Log Management

Nginx generates access and error logs that provide valuable insights into server performance and potential issues. Access logs are located at /var/log/nginx/access.log, while error logs are at /var/log/nginx/error.log.

Configure log rotation to prevent log files from consuming excessive disk space:

sudo nano /etc/logrotate.d/nginx

Monitor real-time access patterns using tail:

sudo tail -f /var/log/nginx/access.log

Regular Maintenance Tasks

Establish a routine maintenance schedule to ensure optimal Nginx performance. Update the system and Nginx packages regularly:

sudo dnf update nginx

Backup configuration files before making changes:

sudo tar -czf nginx-config-backup-$(date +%Y%m%d).tar.gz /etc/nginx/

Test configuration syntax after any modifications to prevent service disruptions:

sudo nginx -t && sudo systemctl reload nginx

Troubleshooting Common Issues

Installation Problems

If package installation fails, verify repository connectivity and check for conflicting packages. Resolve dependency issues by updating the package database:

sudo dnf clean all
sudo dnf makecache

Permission errors during installation typically indicate insufficient user privileges. Ensure you’re using sudo or running commands as root.

Configuration Errors

Syntax errors in configuration files prevent Nginx from starting or reloading. Always test configuration changes:

sudo nginx -t

Common syntax errors include missing semicolons, unmatched braces, and invalid directive contexts. The nginx -t command provides specific line numbers for syntax errors.

Runtime Issues

Service startup failures often result from port conflicts or permission issues. Check if another service is using port 80:

sudo netstat -tlnp | grep :80

Verify file permissions for configuration and content directories ensure the nginx user can read necessary files.

Comparison with Other Web Servers

Nginx offers several advantages over Apache HTTP Server, particularly in high-concurrency scenarios. While Apache uses a process-per-connection model, Nginx’s event-driven architecture handles thousands of simultaneous connections with minimal memory overhead.

Apache excels in flexibility and module ecosystem, making it ideal for complex configurations requiring extensive customization. Nginx provides superior performance for serving static content and acting as a reverse proxy, making it preferred for high-traffic websites and microservice architectures.

For simple websites with moderate traffic, both servers perform adequately. However, Nginx’s lower resource consumption and superior scalability make it the preferred choice for modern web applications and cloud deployments.

Congratulations! You have successfully installed Nginx. Thanks for using this tutorial for installing the Nginx web server on your Rocky Linux 10 system. For additional help or useful information, we recommend you check the official Nginx website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button