Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code: Skills Get Started
FAQ’s Sections
Administration Linux

Installing and Configuring Nginx on CentOS 7: A Complete Step-by-Step Guide

Nginx is one of the most powerful and widely adopted open-source web servers in the world. Known for its exceptional performance, low memory footprint, and ability to handle thousands of concurrent connections, Nginx is the go-to solution for serving static content, acting as a reverse proxy, and performing load balancing across distributed systems.

Whether you are running a personal blog, a high-traffic e-commerce platform, or a complex microservices architecture, Nginx delivers the speed and reliability your users demand. This comprehensive guide walks you through every step of installing, configuring, securing, and optimizing Nginx on a CentOS 7 server β€” from initial system preparation to enabling HTTPS with a free Let's Encrypt SSL certificate.

> Prerequisites: A CentOS 7 server with root or sudo access. If you need a reliable, high-performance environment to follow along, consider exploring VPS Hosting from AlexHost β€” purpose-built for demanding workloads with full root access and SSD storage.

Step 1: Update Your System

Before installing any new software, it is critical to ensure your CentOS 7 system is fully up to date. Outdated packages can introduce security vulnerabilities and dependency conflicts that complicate the installation process.

Open your terminal and run the following command:

sudo yum update -y

This command updates all installed packages to their latest available versions. The -y flag automatically confirms all prompts, making the process non-interactive. Allow the update to complete fully before proceeding.

Step 2: Install Nginx via YUM

Nginx is not available in the default CentOS 7 base repositories. You must first install the EPEL (Extra Packages for Enterprise Linux) repository, which provides a wide range of additional software packages for RHEL-based distributions.

Install the EPEL repository:

sudo yum install epel-release -y

Install Nginx:

sudo yum install nginx -y

This command downloads and installs Nginx along with all required dependencies. Once the installation completes, you can verify the installed version with:

nginx -v

You should see output similar to:

nginx version: nginx/1.20.x

Step 3: Start and Enable the Nginx Service

With Nginx installed, you need to start the service and configure it to launch automatically every time the server reboots.

Start the Nginx service:

sudo systemctl start nginx

Enable Nginx to start on boot:

sudo systemctl enable nginx

Check the service status to confirm it is running:

sudo systemctl status nginx

You should see output indicating that the service is active (running):

● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; ...)
   Active: active (running) since ...

If the service fails to start, review the error logs at /var/log/nginx/error.log for diagnostic information.

Step 4: Configure the Firewall

CentOS 7 uses firewalld as its default firewall management tool. By default, HTTP (port 80) and HTTPS (port 443) traffic are blocked. You must explicitly open these ports to allow web traffic to reach your Nginx server.

Allow HTTP traffic:

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

Allow HTTPS traffic:

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

Reload the firewall to apply the changes:

sudo firewall-cmd --reload

Verify the active rules:

sudo firewall-cmd --list-all

You should see both http and https listed under the services section of the output. If your server is hosted behind an external firewall or security group (common with cloud providers), ensure those rules are also updated to permit traffic on ports 80 and 443.

Step 5: Verify the Installation

To confirm that Nginx is installed correctly and serving content, open a web browser and navigate to your server's public IP address:

http://your_server_ip

You should be greeted by the default Nginx welcome page, which displays the message *"Welcome to nginx!"*. This confirms that the web server is operational and accessible from the internet.

If you do not see the welcome page, double-check the following:

  • The Nginx service is running (sudo systemctl status nginx)
  • The firewall rules are correctly applied
  • Your server's IP address is correct
  • No other service (such as Apache) is occupying port 80

Step 6: Configure Nginx Server Blocks

Nginx uses server blocks (functionally equivalent to Apache's virtual hosts) to define how it handles requests for different domains or subdomains. Each server block is typically stored as a separate configuration file inside the /etc/nginx/conf.d/ directory.

The main Nginx configuration file is located at /etc/nginx/nginx.conf. It includes a directive that automatically loads all .conf files from the conf.d directory, keeping your configuration modular and easy to manage.

Step 6a: Create a New Server Block Configuration File

Create a new configuration file for your domain. Replace example.com with your actual domain name:

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

Add the following server block configuration:

server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/example.com/html;
    index index.html index.htm index.php;

    # Logging
    access_log /var/log/nginx/example.com.access.log;
    error_log  /var/log/nginx/example.com.error.log;

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

    # Deny access to hidden files
    location ~ /. {
        deny all;
    }
}

Key directives explained:

DirectiveDescription
listen 80Instructs Nginx to listen for incoming connections on port 80 (HTTP)
server_nameDefines the domain names this server block responds to
rootSpecifies the document root directory where website files are stored
indexDefines the default files Nginx will serve when a directory is requested
try_filesAttempts to serve the requested URI as a file, then as a directory, and returns a 404 if neither exists
access_log / error_logDefines separate log files for this virtual host for easier debugging

Save the file and exit the editor (Ctrl+X, then Y, then Enter in nano).

Step 7: Create the Document Root and Test File

Create the document root directory that you defined in the server block configuration:

sudo mkdir -p /var/www/example.com/html

Create a simple index.html file to verify that the server block is working correctly:

echo "<h1>Welcome to Example.com β€” Powered by Nginx on CentOS 7!</h1>" | sudo tee /var/www/example.com/html/index.html

Set the correct ownership and permissions so that Nginx can read the files:

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

> Note on SELinux: CentOS 7 ships with SELinux enabled by default. If Nginx cannot read your web files even with correct permissions, you may need to apply the appropriate SELinux context:

> β€œ`bash

> sudo chcon -Rt httpd_sys_content_t /var/www/example.com/

> β€œ`

Step 8: Test the Nginx Configuration

Before restarting Nginx to apply your new configuration, always test for syntax errors. A misconfigured file can bring down your entire web server.

Run the configuration test:

sudo nginx -t

A successful test produces the following output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

If errors are reported, carefully review the indicated line numbers in your configuration files and correct any issues before proceeding.

Restart Nginx to apply the changes:

sudo systemctl restart nginx

Alternatively, if you want to reload the configuration without dropping active connections (recommended for production environments), use:

sudo systemctl reload nginx

Now navigate to your domain in a browser. You should see your custom index.html page.

Step 9: Set Up HTTPS with Let's Encrypt

Running a website over plain HTTP exposes your users to potential eavesdropping and man-in-the-middle attacks. Securing your site with HTTPS is no longer optional β€” it is a fundamental requirement for user trust, data integrity, and search engine ranking.

Let's Encrypt provides free, automated, and trusted SSL/TLS certificates. You can also explore premium SSL Certificates from AlexHost for extended validation and organization-validated options that offer higher levels of trust for business websites.

Install Certbot and the Nginx Plugin

sudo yum install certbot python2-certbot-nginx -y

Obtain and Install the SSL Certificate

Run Certbot with the --nginx plugin, which automatically modifies your Nginx configuration to enable HTTPS:

sudo certbot --nginx -d example.com -d www.example.com

Follow the interactive prompts:

  1. Enter your email address for renewal notifications
  2. Agree to the Let's Encrypt Terms of Service
  3. Choose whether to redirect HTTP traffic to HTTPS (strongly recommended β€” select option 2)

Certbot will automatically:

  • Obtain a signed certificate from Let's Encrypt
  • Modify your /etc/nginx/conf.d/example.com.conf to include SSL directives
  • Configure an HTTP-to-HTTPS redirect

After completion, verify the HTTPS configuration by visiting:

https://example.com

Your browser should display a padlock icon, confirming that the connection is encrypted.

Step 10: Automate Certificate Renewal

Let's Encrypt certificates are valid for 90 days. Failing to renew them before expiry will cause your site to display security warnings to visitors, severely impacting user trust and traffic.

Test the Renewal Process

Before setting up automation, verify that the renewal process works correctly:

sudo certbot renew --dry-run

A successful dry run confirms that automatic renewal will work without issues.

Set Up a Cron Job for Automatic Renewal

Open the root crontab:

sudo crontab -e

Add the following line to check for and renew certificates twice daily (the recommended frequency):

0 0,12 * * * /usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx"

Explanation of the cron schedule:

    0 0,12 * * * β€” Runs at midnight and noon every day
    --quiet β€” Suppresses output unless an error occurs
    --post-hook "systemctl reload nginx" β€” Reloads Nginx after a successful renewal to apply the new certificate without downtime
    
    Save and exit the crontab editor. Your SSL certificates will now renew automatically, keeping your site secure without any manual intervention.
    Performance Optimization Tips for Nginx on CentOS 7
    Once your basic setup is complete, consider these configuration enhancements to maximize Nginx performance:
    Enable Gzip Compression
    Add the following to your nginx.conf within the http {} block to reduce the size of responses sent to clients:
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
    Configure Browser Caching
    Add cache-control headers for static assets to reduce server load and improve page load times:
    location ~* .(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }
    Tune Worker Processes
    In /etc/nginx/nginx.conf, set the number of worker processes to match your server's CPU core count:
    worker_processes auto;
    worker_connections 1024;
    > For resource-intensive applications or high-traffic websites, consider upgrading to Dedicated Servers from AlexHost, which provide guaranteed CPU, RAM, and storage resources with no noisy-neighbor effects.
    Managing Multiple Websites with Nginx
    One of Nginx's greatest strengths is its ability to host multiple websites on a single server through server blocks. For each additional domain, simply:
    
    Create a new .conf file in /etc/nginx/conf.d/
  • Define a unique server_name directive
  • Point the root directive to the appropriate document root
  • Run sudo nginx -t and sudo systemctl reload nginx
  • If you prefer a graphical interface for managing your web server, virtual hosts, databases, and email accounts, consider VPS with cPanel β€” a fully managed control panel solution that simplifies server administration without sacrificing flexibility.

    Alternatively, explore the full range of VPS Control Panels available from AlexHost, including Plesk, DirectAdmin, and other options suited to different workflows and technical preferences.

    Troubleshooting Common Nginx Issues on CentOS 7

    ProblemLikely CauseSolution
    Nginx fails to startPort 80/443 already in useRun `sudo ss -tlnpgrep :80` to identify the conflicting process
    403 Forbidden errorIncorrect file permissions or SELinux contextCheck chmod/chown and apply chcon for SELinux
    502 Bad GatewayUpstream backend (PHP-FPM, Node.js) not runningVerify the backend service is active and the socket/port is correct
    SSL certificate not renewingCertbot cannot bind to port 80Ensure port 80 is open and no other process is blocking it
    Changes not taking effectConfiguration not reloadedRun sudo systemctl reload nginx after every configuration change

    Conclusion

    You have now successfully installed, configured, and secured Nginx on CentOS 7. Your server is ready to host websites with high performance, handle concurrent connections efficiently, and serve content over encrypted HTTPS connections β€” all essential qualities for a modern, production-grade web environment.

    Here is a summary of what was accomplished:

    • βœ… Updated the CentOS 7 system and installed Nginx via the EPEL repository
    • βœ… Started and enabled the Nginx service for automatic startup on boot
    • βœ… Configured firewalld to permit HTTP and HTTPS traffic
    • βœ… Created and configured a custom server block for a domain
    • βœ… Set correct file permissions and SELinux contexts for the document root
    • βœ… Tested the configuration for syntax errors before applying changes
    • βœ… Secured the site with a free Let's Encrypt SSL certificate via Certbot
    • βœ… Automated certificate renewal with a cron job

    Maintaining a secure and high-performing web server requires ongoing attention. Keep Nginx updated regularly, monitor your access and error logs, and review your configuration as your site's requirements evolve.

    If you are looking for a robust hosting foundation for your Nginx-powered projects, AlexHost offers a full spectrum of solutions β€” from entry-level Shared Web Hosting for smaller sites to high-performance VPS and dedicated infrastructure for demanding applications. Every plan is backed by enterprise-grade hardware, 24/7 technical support, and a commitment to uptime and security.