Language: EN

cheatsheet-nginx

Nginx CheatSheet

Nginx is a high-performance web server, reverse proxy, load balancer, and cache server. It is known for its ability to handle multiple simultaneous connections with minimal resource consumption.

Nginx Installation

On Debian/Ubuntu based systems

sudo apt update
sudo apt install nginx

On RHEL/CentOS based systems

sudo yum install epel-release
sudo yum install nginx

On Windows

Download Nginx from nginx.org, and follow the instructions.

Verify Installation

To check if Nginx is running:

sudo systemctl status nginx

Basic Configuration

Configuration File

The main configuration file is located at:

`/etc/nginx/nginx.conf`

Basic Structure of the Configuration File

user www-data;  # User that runs the process
worker_processes auto;  # Worker processes

events {
    worker_connections 1024;  # Max connections per process
}

http {
    include /etc/nginx/mime.types;  # MIME types
    default_type application/octet-stream;  # Default type

    server {
        listen 80;  # Port
        server_name example.com;  # Domain name

        location / {
            root /var/www/html;  # Root directory
            index index.html index.htm;  # Index file
        }
    }
}

Verify Configuration

sudo nginx -t  # Test the configuration

Reload Configuration

sudo systemctl reload nginx  # Reload without stopping the service

Stop and Restart Nginx

sudo systemctl stop nginx  # Stop Nginx
sudo systemctl start nginx  # Start Nginx
sudo systemctl restart nginx  # Restart Nginx

Virtual Server Management

Configure a Virtual Server

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

    root /var/www/example;  # Document root
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;  # Handle 404 errors
    }
}

Redirect HTTP to HTTPS

server {
    listen 80;
    server_name example.com;

    return 301 https://$host$request_uri;  # Redirect to HTTPS
}

Configure HTTPS

server {
    listen 443 ssl;  # Enable SSL
    server_name example.com;

    ssl_certificate /etc/ssl/certs/example.crt;  # SSL Certificate
    ssl_certificate_key /etc/ssl/private/example.key;  # Private Key

    location / {
        root /var/www/example;
        index index.html index.htm;
    }
}

Location Configuration

Default Location

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

Specific Location Redirect

location /old {
    return 301 /new;  # Redirect from /old to /new
}

Location Configuration for Static Files

location /images/ {
    alias /var/www/images/;  # Alias for images directory
}

Performance Optimization

Enable Compression

http {
    gzip on;  # Enable gzip
    gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;  # Types to compress
}

Enable Caching

location / {
    expires 30d;  # Cache for 30 days
}

Load Balancing

Basic Configuration

http {
    upstream myapp {
        server app1.example.com;
        server app2.example.com;
    }

    server {
        listen 80;
        location / {
            proxy_pass http://myapp;  # Pass to upstream group
        }
    }
}

Load Balancing Methods

  • Round Robin (default)
  • Least Connections
upstream myapp {
    least_conn;  # Least connections
    server app1.example.com;
    server app2.example.com;
}

Security

Protect Against DDoS Attacks

http {
    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;  # Limit to 1 request per second

    server {
        location / {
            limit_req zone=mylimit burst=5;  # Allow bursts
        }
    }
}

Configure Security Headers

server {
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Frame-Options DENY;
    add_header Content-Security-Policy "default-src 'self'";
}

These are just examples of commands. A secure configuration is much more complex

Monitoring and Logging

Enable Access Logging

http {
    access_log /var/log/nginx/access.log;  # Access log path
    error_log /var/log/nginx/error.log;  # Error log path
}

Custom Log Format

log_format custom '$remote_addr - $remote_user [$time_local] "$request" '
                 '$status $body_bytes_sent "$http_referer" '
                 '"$http_user_agent" "$http_x_forwarded_for"';

Troubleshooting

Check Logs

For error information:

cat /var/log/nginx/error.log

Set Log Levels

error_log /var/log/nginx/error.log warn;  # Warning level