ConfigGenerator

NGINX Configuration Guide: Rewrites, Redirects & Proxying

Learn how to configure NGINX for URL rewrites, 301 redirects, reverse proxying, and SPA fallbacks with practical examples.

NGINX Configuration Fundamentals

NGINX is one of the most powerful and widely-deployed web servers in the world. Understanding its configuration structure is essential for every DevOps engineer and full-stack developer.

The Server Block

Every NGINX configuration is structured around server blocks, which define how incoming requests are handled:

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

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

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

HTTP to HTTPS Redirect

Always redirect HTTP to HTTPS using a separate server block:

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

SPA (Single Page Application) Fallback

For React, Vue, and Angular apps, serve index.html for all routes:

location / {
    root /var/www/html;
    try_files $uri $uri/ /index.html;
}

URL Rewriting vs Redirecting

  • return 301 — Permanent external redirect. Best for SEO and simple URL changes.
  • rewrite — Internal URL transformation. Use regex for complex path changes.
  • try_files — Check if file/directory exists, then fall back. Essential for SPAs.

Location Block Priority Order

NGINX evaluates location blocks in this precise order:

  1. location = /exact — Exact match (highest priority)
  2. location ^~ /prefix — Prefix match, stops regex evaluation
  3. location ~ ^/regex — Case-sensitive regex match
  4. location ~* /regex — Case-insensitive regex match
  5. location /prefix — Longest prefix match (lowest priority)