Nginx

Nginx (pronounced "engine-x") is a high-performance web server, reverse proxy, and load balancer.

It is widely used for serving websites, handling API requests, and managing network traffic efficiently.

chevron-rightFeatureshashtag

Key Features of Nginx:

  • Web Server: Serves static and dynamic content with high concurrency.

  • Reverse Proxy: Forwards client requests to backend servers.

  • Load Balancer: Distributes traffic among multiple servers.

  • Caching: Improves performance by storing frequently accessed content.

  • Security: Can handle SSL termination and protect against DDoS attacks.

chevron-rightConfigurationshashtag

chevron-rightCommandshashtag

Here’s a comprehensive list of Nginx commands for installation, configuration, management, and troubleshooting.


1️⃣ Install & Uninstall Nginx

Install Nginx

sudo apt update && sudo apt install nginx -y  # Ubuntu/Debian
sudo yum install nginx -y                     # CentOS/RHEL
sudo dnf install nginx -y                     # Fedora

Uninstall Nginx

sudo apt remove --purge nginx -y  # Ubuntu/Debian
sudo yum remove nginx -y          # CentOS/RHEL
sudo dnf remove nginx -y          # Fedora

2️⃣ Start, Stop, Restart, and Enable Nginx

Start Nginx

sudo systemctl start nginx

Stop Nginx

sudo systemctl stop nginx

Restart Nginx

sudo systemctl restart nginx

Reload Nginx (Apply config changes without downtime)

sudo systemctl reload nginx

Enable Nginx on boot

sudo systemctl enable nginx

Disable Nginx from starting on boot

sudo systemctl disable nginx

3️⃣ Check Nginx Status & Logs

Check if Nginx is running

sudo systemctl status nginx

Check Nginx version

nginx -v        # Short version
nginx -V        # Detailed version with compile options

Check Nginx configuration for errors

sudo nginx -t

Check Nginx logs

sudo tail -f /var/log/nginx/access.log  # Access logs
sudo tail -f /var/log/nginx/error.log   # Error logs

4️⃣ Manage Nginx Configuration

Nginx Main Config File

/etc/nginx/nginx.conf

Create a New Site Configuration

sudo nano /etc/nginx/sites-available/mywebsite.conf
sudo ln -s /etc/nginx/sites-available/mywebsite.conf /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/mywebsite.conf

List Enabled Sites

ls /etc/nginx/sites-enabled/

5️⃣ Reload Nginx After Configuration Changes

sudo systemctl reload nginx

6️⃣ Manage Nginx Processes

Check running Nginx processes

ps aux | grep nginx

Kill Nginx process (Force stop)

sudo pkill nginx

or

sudo killall nginx

Restart all Nginx workers

sudo systemctl restart nginx

7️⃣ Firewall Rules for Nginx

Allow HTTP (Port 80) and HTTPS (Port 443)

sudo ufw allow 'Nginx Full'   # Ubuntu (UFW Firewall)
sudo firewall-cmd --add-service=http --permanent  # CentOS
sudo firewall-cmd --add-service=https --permanent
sudo firewall-cmd --reload

Check Allowed Services

sudo ufw status
sudo firewall-cmd --list-all

8️⃣ Test Nginx Configuration

Test syntax before reloading

sudo nginx -t

Simulate an HTTP request to check response

curl -I http://localhost
curl -I https://yourdomain.com

9️⃣ Enable Logging for Debugging

Increase error log level (Edit nginx.conf)

error_log  /var/log/nginx/error.log debug;

Then restart Nginx:

sudo systemctl restart nginx
sudo journalctl -u nginx

🔟 Useful Nginx Commands for Debugging

Check open ports (Make sure Nginx is listening)

sudo netstat -tulnp | grep nginx
sudo ss -tulnp | grep nginx

Check if a domain is resolving to your server

dig yourdomain.com +short
nslookup yourdomain.com

Check if Nginx is proxying correctly

curl -I -H "Host: yourdomain.com" http://localhost

Conclusion

🚀 These commands cover everything from installation to debugging in Nginx.

Would you like specific configurations for load balancing, caching, or SSL? 😃

chevron-rightConfiguration by useshashtag

Here are three separate Nginx configurations for each use case:


1. Web Server (Serving Static & Dynamic Content)

This configuration serves static files from /var/www/html and forwards PHP requests to a backend.

server {
    listen 80;
    server_name example.com;

    root /var/www/html;
    index index.html index.htm index.php;

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

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

2. Reverse Proxy (Forwarding Requests to Backend Server)

This configuration forwards requests to a backend application running on port 5000.

proxy_pass 80/path to backend service, eg 127.0.0.1:8000
server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

3. Load Balancer (Distributing Traffic Among Multiple Servers)

This setup distributes traffic among three backend servers.

Nginx uses Below Load balancing method

Round Robin (Default)

  • Requests are distributed sequentially across all available servers.

  • 1st request to 1st server 2nd to 2nd S and 3rd to 3rd and 4rth request to 1 st server.

upstream backend_servers {
    server 192.168.1.101;
    server 192.168.1.102;
    server 192.168.1.103;
}

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://backend_servers;  
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Let me know if you need any modifications! 🚀

chevron-rightReverse Proxyhashtag

  • Use a Reverse Proxy if you want to protect backend servers, load balance, or improve security.

  • Use a Forward Proxy if you want to control outbound traffic, hide users (client)' identities, or bypass restrictions

Full Nginx Reverse Proxy Configuration File

Here’s a complete Nginx reverse proxy configuration file that: ✅ Routes requests to backend servers ✅ Handles SSL termination ✅ Supports WebSockets ✅ Adds security headers ✅ Caches static content


Step 1: Install Nginx

If you haven’t installed Nginx yet, install it using:


Step 2: Create Reverse Proxy Configuration File

Create a new configuration file in /etc/nginx/sites-available/ (or /etc/nginx/conf.d/ in some setups):

Paste the following configuration:


Step 3: Explanation of Configuration

1️⃣ HTTP to HTTPS Redirect

✅ Redirects all HTTP traffic to HTTPS for security.


2️⃣ SSL Configuration (HTTPS)

✅ Configures SSL/TLS using certificates from Let’s Encrypt or another provider.


3️⃣ Reverse Proxy to Backend Server

Sends requests to backend server running on port 5000. ✅ Passes real client IP to the backend for logging.


4️⃣ WebSocket Support

✅ Supports WebSocket connections for real-time applications (e.g., chat, live updates).


5️⃣ Timeout Settings

✅ Prevents long-running requests from being dropped.


6️⃣ Caching for Static Content

✅ Caches static files for 30 days to improve performance.


7️⃣ Rate Limiting (Optional)

✅ Limits API requests to 10 requests per second per user. ✅ Prevents abuse (DDoS attacks).


Step 4: Enable Configuration

Run the following commands to enable the reverse proxy:


Step 5: Test Reverse Proxy

Run the following command to test the reverse proxy:

✅ If everything is correct, you should receive a 200 OK response.


Conclusion

🚀 This configuration makes Nginx act as a powerful reverse proxy with: ✅ HTTPS & SSL termination ✅ WebSockets support ✅ Security headers ✅ Static content caching ✅ Rate limiting

Would you like a version with multiple backend servers (load balancing)? 🚀

Last updated