How to Install Nginx on CentOS
Nginx is a popular open-source web server that is known for its high performance, stability, and low resource consumption. It is an excellent choice for serving static content, reverse proxying, and load balancing. In this tutorial, we will guide you through the process of installing Nginx on CentOS.
Prerequisites
Before proceeding with the installation, you need to ensure that you have the following requirements:
- A CentOS server with a non-root user with sudo privileges.
- You have updated the system packages to the latest version.
Step 1: Installing Nginx on CentOS
To install Nginx on CentOS, follow the steps below:
First, update the package index by running the command:
sudo yum update
Next, install Nginx by running the command:
sudo yum install nginx
This will download and install Nginx along with its dependencies.
Once the installation is complete, start Nginx by running the command:
sudo systemctl start nginx
This will start the Nginx service on your CentOS server.
Verify that Nginx is running by checking its status using the command:
systemctl status nginx
You should see output similar to the following:
● nginx.service - The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2021-10-20 15:13:31 UTC; 58s ago
Step 2: Configuring Nginx
By default, Nginx will listen on port 80. You can confirm this by opening your web browser and navigating to your server's IP address. You should see the "Welcome to Nginx" page.
To configure Nginx, you need to modify its configuration file located at /etc/nginx/nginx.conf
. You can use your favorite text editor to open the file and make changes. For example, to change the server's default page, you can add the following line to the http
block:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm;
server_name _;
location / {
try_files $uri $uri/ /index.html;
}
}
This configuration block sets the root directory for the server to /var/www/html
and sets the default page to index.html
. It also defines a location block that will serve any requests for files that do not exist by returning the index.html
file.
Once you have made changes to the configuration file, save the changes and test the configuration by running the command:
sudo nginx -t
This command will check the syntax of the configuration file and report any errors. If there are no errors, reload the Nginx configuration by running the command:
sudo systemctl reload nginx
Conclusion
In this tutorial, we showed you how to install and configure Nginx on CentOS. Nginx is a powerful web server that can handle a large number of requests with low resource consumption. By following the steps outlined in this tutorial, you should now have a working Nginx installation on your CentOS server.