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 -yThis 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 -yInstall Nginx:
sudo yum install nginx -yThis command downloads and installs Nginx along with all required dependencies. Once the installation completes, you can verify the installed version with:
nginx -vYou should see output similar to:
nginx version: nginx/1.20.xStep 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 nginxEnable Nginx to start on boot:
sudo systemctl enable nginxCheck the service status to confirm it is running:
sudo systemctl status nginxYou 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=httpAllow HTTPS traffic:
sudo firewall-cmd --permanent --add-service=httpsReload the firewall to apply the changes:
sudo firewall-cmd --reloadVerify the active rules:
sudo firewall-cmd --list-allYou 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_ipYou 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.confAdd 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:
| Directive | Description |
|---|---|
listen 80 | Instructs Nginx to listen for incoming connections on port 80 (HTTP) |
server_name | Defines the domain names this server block responds to |
root | Specifies the document root directory where website files are stored |
index | Defines the default files Nginx will serve when a directory is requested |
try_files | Attempts to serve the requested URI as a file, then as a directory, and returns a 404 if neither exists |
access_log / error_log | Defines 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/htmlCreate 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.htmlSet 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 -tA 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 successfulIf 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 nginxAlternatively, if you want to reload the configuration without dropping active connections (recommended for production environments), use:
sudo systemctl reload nginxNow 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 -yObtain 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.comFollow the interactive prompts:
- Enter your email address for renewal notifications
- Agree to the Let's Encrypt Terms of Service
- 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.confto include SSL directives - Configure an HTTP-to-HTTPS redirect
After completion, verify the HTTPS configuration by visiting:
https://example.comYour 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-runA 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 -eAdd 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/server_name directiveroot directive to the appropriate document rootsudo nginx -t and sudo systemctl reload nginxIf 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
| Problem | Likely Cause | Solution | |
|---|---|---|---|
| Nginx fails to start | Port 80/443 already in use | Run `sudo ss -tlnp | grep :80` to identify the conflicting process |
| 403 Forbidden error | Incorrect file permissions or SELinux context | Check chmod/chown and apply chcon for SELinux | |
| 502 Bad Gateway | Upstream backend (PHP-FPM, Node.js) not running | Verify the backend service is active and the socket/port is correct | |
| SSL certificate not renewing | Certbot cannot bind to port 80 | Ensure port 80 is open and no other process is blocking it | |
| Changes not taking effect | Configuration not reloaded | Run 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.
on All Hosting Services