Skip to content
Velloreth
Developer Tools 7 min read

Nginx Basics: Reverse Proxy, Static Files and TLS

Nginx serves static files and proxies requests. Learn the config structure, the common blocks, and the patterns you need.

By

What Nginx is

Nginx is an event-driven web server. It handles many concurrent connections with a small memory footprint, which is why it is the default in front of most applications.

Its common roles:

  • Static file server — serve HTML, CSS, JS, and images.
  • Reverse proxy — forward requests to an application.
  • TLS terminator — handle HTTPS and pass plain HTTP upstream.
  • Load balancer — distribute across several upstream servers.
  • Cache — store responses to reduce upstream load.

The config structure

The config is a tree of blocks.

main
├── events
└── http
    ├── server
    │   └── location
    └── server
        └── location

http holds settings that apply to all servers.

server defines a virtual host: a listen port and a server name.

location matches a URL path and defines how to handle it.

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

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

Serving static files

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.html;

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

    location /assets/ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

try_files checks each path in order and falls back to the last argument. For a single-page application, the fallback is index.html.

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

root versus alias. This is a common source of 404s.

# root: the location path is appended
location /images/ {
    root /var/www;      # serves /var/www/images/foo.png
}

# alias: the location path is replaced
location /images/ {
    alias /var/www/pics/;  # serves /var/www/pics/foo.png
}

Reverse proxy

The most common use: forward requests to an application.

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        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;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

The headers matter. Without them, the application sees the proxy’s address and the wrong protocol, which breaks redirects, logging, and rate limiting.

Upgrade and Connection are needed for WebSockets.

The trailing slash. This changes the path the upstream receives.

# /api/users -> http://app/api/users
location /api/ {
    proxy_pass http://app;
}

# /api/users -> http://app/users
location /api/ {
    proxy_pass http://app/;
}

With a trailing slash on proxy_pass, the location prefix is stripped. Without it, the full path is passed. This is a frequent source of confusion.

Location matching

Nginx checks locations in a specific order.

  1. Exact match — location = /path
  2. Prefix match with ^~ — takes precedence over regex
  3. Regex match — location ~ pattern, in order
  4. Longest prefix match — the default
location = /health { return 200 "ok"; }        # exact
location ^~ /static/ { root /var/www; }        # prefix, beats regex
location ~ \.php$ { fastcgi_pass ...; }        # regex
location / { proxy_pass http://app; }          # prefix

The ^~ modifier is useful when a prefix should not be overridden by a regex.

TLS

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

    add_header Strict-Transport-Security "max-age=31536000" always;

    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

The second server redirects HTTP to HTTPS.

Compression and caching

gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;
gzip_comp_level 5;

location ~* \.(jpg|jpeg|png|gif|ico|svg|woff2)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    access_log off;
}

Do not gzip images. They are already compressed, and gzipping them wastes CPU for no gain.

immutable tells the browser never to revalidate, which is safe for a hashed filename.

Load balancing

upstream app {
    least_conn;
    server 10.0.0.1:3000;
    server 10.0.0.2:3000;
    server 10.0.0.3:3000 backup;
}

server {
    location / {
        proxy_pass http://app;
    }
}

Strategies: round-robin (default), least_conn, ip_hash (sticky sessions), and random.

backup marks a server that is used only when the others are down.

Rate limiting

limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

server {
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://app;
    }
}

The zone stores the state, and burst allows a short spike. nodelay serves the burst immediately rather than queueing it.

Testing and reloading

nginx -t              # validate the config
nginx -s reload       # reload without downtime
nginx -s stop         # stop

nginx -t before every reload. A syntax error in a reload leaves the old config running, but a restart with a bad config fails to start.

The reload starts new workers and gracefully shuts down the old ones, so in-flight requests complete.

Security headers

Nginx is a convenient place to add security headers, because it applies them to every response.

add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'" always;

The always parameter matters. Without it, the header is added only for successful responses, so an error page is missing it.

A Content-Security-Policy needs care. A policy that is too strict breaks the site, and one that is too loose provides no protection. Start with Content-Security-Policy-Report-Only to see what would break before enforcing it.

HSTS should be added only once HTTPS works reliably, because it tells the browser to refuse HTTP for the domain.

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Logging

Nginx logs every request by default, and the format is configurable.

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

access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;

$request_time is the total time, which is the number to watch for slow requests.

JSON logs are easier to search and aggregate.

log_format json escape=json '{"time":"$time_iso8601","ip":"$remote_addr",'
                            '"method":"$request_method","uri":"$request_uri",'
                            '"status":$status,"rt":$request_time}';

Turn off logging for static assets to reduce noise and disk usage.

location ~* \.(jpg|png|css|js|woff2)$ {
    access_log off;
}

Common mistakes

Forgetting the proxy headers. The application sees the proxy’s address and the wrong protocol, which breaks redirects, logging, and rate limiting. This is the most common Nginx mistake.

The trailing slash on proxy_pass. With a trailing slash the location prefix is stripped; without it the full path is passed. A mismatch here produces 404s that are hard to diagnose, because the request reaches the application with an unexpected path.

Using root where alias is needed. root appends the location path to the directory, and alias replaces it. A location that serves files from a different directory needs alias.

A regex location that shadows a prefix. A regex is checked before the longest prefix match, so a broad regex can capture requests meant for a specific prefix. The ^~ modifier prevents this.

Reloading without validating. nginx -t before every reload. A syntax error in a reload leaves the old config running, but a restart with a bad config fails to start, which takes the site down.

Gzipping images. They are already compressed, so gzipping them wastes CPU for no gain. Restrict gzip_types to text formats.

A missing always on a security header. Without it, the header is added only for successful responses, so an error page is missing it.

Practical guidance

  • Set the proxy headers so the app sees the real host and IP.
  • Watch the trailing slash on proxy_pass.
  • Use try_files for a single-page application.
  • Remember root appends and alias replaces.
  • Use ^~ when a prefix should beat a regex.
  • Do not gzip images.
  • Run nginx -t before reloading.
  • Redirect HTTP to HTTPS.

For the related guides, see docker-basics-guide and how-cdns-actually-work. For the broader context, http-status-codes-explained and rest-api-rate-limiting.

Quotable summary

Nginx is an event-driven web server that handles many concurrent connections with a small memory footprint, and its config is a tree of blocks where http contains server and server contains location. A reverse proxy forwards requests to an upstream application, which is the most common use, and you must set proxy headers so the application knows the original host, protocol, and client IP. Location matching has a precedence order — exact match, then prefix with ^~, then regex, then the longest prefix — and the exact match wins over a prefix match. Always set proxy headers, watch the trailing slash on proxy_pass because it changes the path the upstream receives, and run nginx -t before every reload.

Frequently asked questions

What is a reverse proxy?
A server that receives client requests and forwards them to an upstream application, returning the response. It hides the application, terminates TLS, and can cache, compress, and rate-limit.
What is the difference between a root and an alias in Nginx?
root appends the location path to the directory, while alias replaces the location path with the directory. This is a common source of 404s.
How does Nginx choose a location block?
It checks exact matches first, then the longest prefix match, then regular expressions in order. The = modifier forces an exact match and ^~ makes a prefix match take precedence over regex.
Why does my application see the wrong client IP?
Because the request comes from the proxy, not the client. Set X-Real-IP and X-Forwarded-For in the proxy headers, and configure the application to trust them.
What is the difference between proxy_pass with and without a trailing slash?
With a trailing slash, the location prefix is replaced by the proxy path. Without it, the full original path is passed. This changes the URL the upstream receives.
How do I reload Nginx without downtime?
Run nginx -t to validate the config, then nginx -s reload. The reload starts new worker processes and gracefully shuts down the old ones, so in-flight requests complete.