Nginx Install on CentOS with Server Blocks

Written by:

The installation of Nginx on Linux distributions is straightforward. This article specifically utilizes CentOS 7.

NOTE 1: An active internet connection is required on the VM for this installation.

NOTE 2: If you try to install the NGinx using the yum without first installing the EPEL repository, you will see the below message.

1 – Installation of the EPEL repository

yum install epel-release -y

2 – Installation of the Nginx

yum install nginx -y

3 – Starting the Nginx service and Enabling it on the system boot

systemctl start nginx

systemctl enable nginx

4 – Confirming the Nginx service is running

systemctl status nginx

5 – Checking if the firewall is set to accept HTTP (port 80) requests. In my case, it is not.

firewall-cmd --list-all

6 – Adding a firewall rule on the CentOS to accept HTTP (port 80) requests.

firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --reload
firewall-cmd --list-all

You can see the “HTTP” was added under “services”.

To verify the Nginx’s functionality, open a browser and enter the Linux machine’s IP address or hostname. The default Nginx page should appear as below.

8 –  The above page’s locations is located at /usr/share/nginx/html

9 – To effectively set up the Server blocks and experiment with multiple ports serving diverse content, begin by creating two new folders, each dedicated to a specific content type, as outlined below.

mkdir website01 website02 
ls

10 – Create sample index.html files, one for each of the folders created. These files will be used by their respective HTTP://IP:PORT

echo "Web Server 01 - Test Page Nginx" > website01/index.html
echo "Web Server 02 - Test Page Nginx" > website02/index.html

11 – Navigate to the Nginx default location for service block files and create your file

cd /etc/nginx/conf.d touch default.conf

12 – Edit the “default.conf” file either with “vi” or “nano” and paste the below lines


server {
listen 80 default_server;server_name willianit.lab.net www.willianit.lab.net;
root /usr/share/nginx/website01;
index index.html;
try_files $uri /index.html;
}


server {
listen 81 default_server;
server_name willianit.lab.net www.willianit.lab.net;
root /usr/share/nginx/website02;
index index.html;
try_files $uri /index.html;

}


13 – Open your browser again and type your Linux IP. You will see the new home page we created before.

14 – Before trying the second page (port 81), allow the TCP port 81 in the firewall

firewall-cmd --zone=public --permanent --add-port=81/tcp
firewall-cmd --reload
firewall-cmd --list-ports

15 – Open a new page/tab and access HTTP://your-linux-ip:81. You will see the second page.

Nginx Server block is configured.

Leave a Reply

Your email address will not be published. Required fields are marked *