How to install and configure Nginx on RHEL/AlmaLinux
-
Check if Nginx is already installed
rpm -qa | grep nginx
-
Install nginx
dnf install -y nginx
-
Check which service is using port 80
ss -tulpn | grep :80
In this example, the
httpdservice is already listening on port 80. -
Stop the httpd service and disable it
systemctl stop httpd systemctl disable httpdBy default, Nginx listens on port 80. If Apache (
httpd) is already using that port, Nginx cannot bind to it.Stopping Apache prevents this port conflict.
-
Enable and start the service
systemctl enable --now nginx
-
Verify Nginx is listening on port 80
ss -tulpn | grep :80
You should now see Nginx listening on port 80.
-
View the main configuration file
cat /etc/nginx/nginx.confThe main configuration file controls Nginx’s global settings and defines configuration contexts such as
eventsandhttp. -
Understand the Include directive
Inside the
httpblock, you will find:
Meaning:
include= Loads additional configuration files.-
/etc/nginx/conf.d/= Directory containing additional Nginx configuration files. -
.conf= Loads all files ending in.conf.
This allows us to create separate server block configuration files instead of modifying the main
nginx.conffile. -
Create the server block
Create a new configuration file:
vi /etc/nginx/conf.d/my-blog.confAdd
server { listen 3000; server_name _; root /var/www/my-block/html; index index.html; location / { try_files $uri $uri/ =404; } }
Directive Purpose listen 3000;Listen on TCP port 3000. server_name _;Catch-all server name. rootDefines the website document root. indexSpecifies the default webpage. location /Handles requests to the root URL and its paths. try_filesChecks whether the requested file exists; returns 404 if not. -
Create the website directory and HTML file
Create the document root and create the HTML file:
mkdir -p /var/www/my-block/html vi /var/www/my-block/html/index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Structure of HTML Document</title> <style> body { margin: 0; min-height: 100vh; display: grid; place-content: center; text-align: center; background: #000; color: #fff; font-family: Georgia, serif; } h1 { font-size: 3rem; font-weight: 400; letter-spacing: 1px; margin: 0; } p { color: #aaa; font-size: 1.1rem; margin-top: 1rem; } </style> </head> <body> <!-- Main content of website --> <h1>Welcome to My First Website running on port 3000</h1> <p>Thanks for visiting my website <3</p> </body> </html>
-
Test the Nginx configuration
nginx -t
-
Restart nginx
systemctl restart nginx
-
Access your webpage
Accessing http://<your_server_IP>:3000
You can also test locally:
curl http://localhost:3000