How to Install Nginx on CentOS 7

May 12, 2024

To install on CentOS 7, follow the steps below.

Step 1 : Update:

sudo yum update

Step 2 : Install Nginx:

sudo yum install nginx

Step 3 : Check Nginx version:

nginx -v

Step 4 : Enable and start Nginx service:

sudo systemctl enable nginx --now

Step 5 : Step 5: Check Nginx status:

sudo systemctl status nginx

Step 6 : Adjust Firewall:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https

Step 7 : Reload Firewall:

sudo firewall-cmd --reload

Step 8 : Create a configuration file for your domain, for example, example.com:

sudo nano /etc/nginx/conf.d/example.com.conf

Add the following configuration to the file:

server {
    listen 80;

    server_name example.com www.example.com;

    root /var/www/html/example.com;
    index index.html;

    location / {
        try_files $uri $uri/ =404;

Step 9 : Create root directory for domain.com

sudo mkdir -p /var/www/html/example.com

Step 10 : Create index.html file

sudo nano /var/www/html/example.com/index.html

Add content to the index.html file:

<!DOCTYPE html>
    <title>Welcome to example.com</title>
    <h1>Welcome to example.com!</h1>
    <p>This is the default index.html page for your domain.</p>

Step 11 : If SELinux is enabled, set appropriate context

sudo semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/example.com(/.*)?"
sudo restorecon -Rv /var/www/html/example.com

Step 12 : Test Nginx configuration:

sudo nginx -t

Step 13 : Restart Nginx:

sudo systemctl restart nginx

Step 14 : Open a web browser and enter your server's IP address or domain name to verify Nginx is serving pages.

Congratulations, you have successfully installed Nginx on CentOS 7.