Installing and Configuring Nginx on CentOS 7
Nginx is a high-performance web server and reverse proxy server that is widely used for serving static content, handling concurrent connections, and load balancing. This guide will walk you through the installation and configuration of Nginx on a CentOS 7 server.
1. Update Your System
Before installing Nginx, ensure your system is up to date. Open the terminal and run the following commands:
2. Install Nginx
To install Nginx, you can use the default package manager yum:
This command installs Nginx and any required dependencies.
3. Start and Enable Nginx
After installation, start the Nginx service and enable it to start automatically on boot:
4. Configure the Firewall
To allow web traffic to your server, you need to configure the firewall to allow HTTP and HTTPS traffic. Use the following commands to open the necessary ports:
5. Verify the Installation
To verify that Nginx is installed and running, open your web browser and navigate to your server’s IP address:
You should see the default Nginx welcome page, which indicates that the installation was successful.
6. Configuring Nginx
Nginx configuration files are located in /etc/nginx/. The main configuration file is nginx.conf, and server blocks (similar to virtual hosts in Apache) are defined in the conf.d directory.
Step 1: Create a New Server Block
To create a new server block for your website, create a new configuration file in the /etc/nginx/conf.d/ directory. For example, create a file named example.com.conf:
Add the following configuration:
Replace example.com with your domain name and adjust the root directory to match where your website files will be located.
Step 2: Create the Document Root
Next, create the document root directory for your website:
You can also create an example index.html file to test:
7. Test Nginx Configuration
Before applying the changes, test the Nginx configuration for any syntax errors:
If the output shows that the configuration is successful, proceed to restart Nginx to apply the changes:
8. Setting Up HTTPS with Let’s Encrypt (Optional)
To secure your website with SSL, you can use Let’s Encrypt to obtain a free SSL certificate. First, install Certbot:
Then run Certbot to obtain and install the SSL certificate:
Follow the prompts to complete the installation. Certbot will automatically configure Nginx to use SSL.
9. Automatic Certificate Renewal
Let’s Encrypt certificates are valid for 90 days. To set up automatic renewal, add a cron job:
Add the following line to check and renew certificates daily:
10. Conclusion
You have successfully installed and configured Nginx on CentOS 7. Nginx is now ready to serve your website, and you have the option to secure it with SSL using Let’s Encrypt. Regularly monitor your server and keep Nginx updated to maintain performance and security.