Nginx - How to use

Commands

  • For Installing:

sudo apt update

sudo apt upgrade

sudo apt install nginx

  • For starting:

sudo systemctl start nginx

sudo systemctl enable nginx

  • For checking the status:

sudo systemctl status nginx

  • For reloading anytime, any config file has changed:

sudo systemctl reload nginx

  • For restarting:

sudo systemctl restart nginx

  • Test the Nginx configuration for syntax errors:

sudo nginx -t

Uses

Nginx serves many purposes, some of them are:

  1. Web Server

    Default Configurations

    After installing Nginx, open your web browser and navigate to http://your_server_ip. You should see the Nginx default welcome page.

    Default page configurations can be seen at → /etc/nginx/sites-available/default

     server {
     listen 80;  # Listen on port 80, the default HTTP port
     server_name localhost;  # The server name, here it is set to localhost
    
     # root and index are directives or keywords
     root /var/www/html;  # The root directory where files are served from
     index index.html index.htm index.nginx-debian.html;  # The default files to serve
    
     location / {
         try_files $uri $uri/ =404;  # Try to serve the requested URI, if not found return a 404
         }
     }
    
    • We can serve static files using this process.

    • use <domain_name> instead of localhost for serving the index.html page when opening the <domain_name>.

How to serve static files on different domain names

1️⃣ Create a new config file

    sudo nano /etc/nginx/sites-available/practice1

Add this:

    server {
        listen 80;
        server_name practice1.heysohail.me;

        root /var/www/html/practice1;
        index index.html;

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

2️⃣ Create the directory and make your index.html there

    sudo mkdir -p /var/www/html/practice1
    sudo vim /var/www/html/practice1/index.html

3️⃣ Enable the config

    sudo ln -s /etc/nginx/sites-available/practice1 /etc/nginx/sites-enabled/

4️⃣ Restart Nginx

    sudo systemctl restart nginx

Now, practice1.heysohail.me will serve files from /var/www/html/practice1/.

  1. Reverse Proxy

  2. Rate Limiter

  3. Cache

  4. Load Balancer

📌 We will be covering the left topics in the coming days. Stay tuned!

0
Subscribe to my newsletter

Read articles from Md Sohail Ansari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Md Sohail Ansari
Md Sohail Ansari

Final Year Undergrad at IIIT Bhagalpur and a Full Stack Web Developer. Portfolio: https://www.heysohail.me/