Nginx Reference

Jan 5, 2026

Nginx is a fast, efficient web server that handles lots of concurrent connections without eating your RAM. It’s used for serving sites, routing traffic, and load balancing.

Root vs Alias

location /admin/ {
  root /var/www/locked;
}

Request for /admin/secret.html looks at /var/www/locked/admin/secret.html. Notice it kept the /admin/ part.

location /admin/ {
  alias /var/www/locked/;
}

Same request now looks at /var/www/locked/secret.html, the /admin/ got swapped out (always add the trailing slash with alias or things break).

Index Files

server {
  root /var/www/html;
  index index.html index.htm;
}

It tries each file in order and uses the first one it finds.

Error Pages

server {
  error_page 404 /errors/not_found.html;
  error_page 500 502 503 504 /errors/server_error.html;

  location ^~ /errors/ {
    internal;
  }
}
error_page 404 =200 /index.html;

Try Files

location / {
  try_files $uri $uri.html $uri/ /index.html;
}
location / {
  try_files $uri @backend;
}

location @backend {
  proxy_pass http://127.0.0.1:8080;
}

Request Body Handling

client_body_buffer_size 16k;
location /upload/ {
  client_body_buffer_size 128k;
  client_max_body_size 5G;
}
client_body_temp_path /mnt/ssd/nginx-temp 1 2;

The numbers create nested directories to avoid too many files in one folder.

Method Restrictions

location /admin/ {
  limit_except GET {
    allow 192.168.1.0/24;
    deny all;
  }
}

Everyone can GET. Only local IPs can POST/PUT/DELETE.

location /api/ {
  limit_except GET HEAD OPTIONS {
    deny all;
  }
}

Rate Limiting

location /downloads/ {
  limit_rate 500k;
}
location /videos/ {
  limit_rate_after 10m;
  limit_rate 500k;
}
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

location /api/ {
  limit_req zone=api burst=20 nodelay;
}

Example

http {
  limit_req_zone $binary_remote_addr zone=general:10m rate=50r/s;

  server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    
    client_max_body_size 100m;

    location / {
      limit_req zone=general burst=100 nodelay;
      try_files $uri $uri/ /index.html;
    }

    location /api/ {
      limit_rate 2m;
      
      limit_except GET POST {
        deny all;
      }

      proxy_pass http://api_backend;
    }

    location /admin/ {
      limit_except GET {
        allow 192.168.1.0/24;
        deny all;
      }

      auth_basic "Admin Area";
      auth_basic_user_file /etc/nginx/.htpasswd;
      alias /var/www/admin/;
    }

    error_page 404 /errors/404.html;
    error_page 500 502 503 504 /errors/500.html;

    location ^~ /errors/ {
      internal;
    }
  }
}

Quick Tips

Size Units