Nginx Reverse Proxy Builder · Microservices / Gateway

Nginx Multi-Service Subpath Routing Config (/api/, /auth/ & /ws/)

Generate an Nginx reverse proxy server block for Microservices / Gateway with URL prefix rewrite previews, Certbot SSL redirects, WebSocket upgrade headers, and Docker DNS checks.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Domain, Routing & Upstream

2. TLS, WebSockets & Directives

# /etc/nginx/sites-available/gateway.example.com.conf
# Generated by OpsCheck DevTools — Validate with: sudo nginx -t && sudo systemctl reload nginx

# Required in http {} context (or top of sites-available file) for clean WebSocket upgrades
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    listen [::]:80;
    server_name gateway.example.com;

    # Redirect all plaintext HTTP traffic permanently to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name gateway.example.com;

    # Let's Encrypt Certbot TLS Certificates
    ssl_certificate     /etc/letsencrypt/live/gateway.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/gateway.example.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    client_max_body_size 50M;

    # Gzip compression for JSON, JS, CSS, and SVG responses
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;

    # Baseline HTTP Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location /api/ {
        # Re-resolve Docker service IPs dynamically to avoid 502 after container restarts
        resolver 127.0.0.11 valid=30s ipv6=off;
        set $upstream_endpoint http://api_service:8000;
        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass $upstream_endpoint;
        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 X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;

        # WebSocket & Upgrade support (requires map $http_upgrade $connection_upgrade)
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_cache_bypass $http_upgrade;

        proxy_connect_timeout 15s;
        proxy_send_timeout 120s;
        proxy_read_timeout 120s;
    }
}
$sudo nginx -t && sudo systemctl reload nginx
URL Routing TransformationPrefix Stripped
GET https://gateway.example.com/api/usershttp://api_service:8000/users

Strip Prefix ON: Nginx strips '/api/' via trailing-slash proxy_pass so upstream receives '/users'.

Configuration Diagnostics

  • infoPrefix Stripping Active (/api/ -> /)

    GET https://gateway.example.com/api/users -> Upstream receives http://api_service:8000/users. Strip Prefix ON: Nginx strips '/api/' via trailing-slash proxy_pass so upstream receives '/users'.

  • passWebSocket Upgrade & Extended Timeout (120s) Enabled

    Configured HTTP/1.1 Upgrade, Connection $connection_upgrade map, and extended proxy_read_timeout for persistent real-time sockets.

  • passDocker Embedded DNS Resolver (127.0.0.11) Active

    Using variable-based proxy_pass with resolver 127.0.0.11 valid=30s prevents stale container IP crashes when "api_service" restarts or scales.

  • infoSingle-Layer CORS Policy Reminder

    This configuration intentionally omits Access-Control-Allow-Origin headers so your upstream backend framework (Laravel, FastAPI, Express, ASP.NET Core) owns CORS cleanly without duplicate header rejections.

Runs locally in your browser. Domain names and upstream topology are never sent to a server.

Common Nginx Error Log Pattern (Microservices / Gateway)

When upstream sockets, timeouts, body limits, or Docker DNS rules are misconfigured for Microservices / Gateway, Nginx typically records an entry matching the log line below inside /var/log/nginx/error.log:

/var/log/nginx/error.log

2026/11/22 20:41:19 [error] 9012#9012: *1540 open() "/etc/nginx/html/auth/token" failed (2: No such file or directory), client: 198.51.100.44, server: gateway.example.com, request: "POST /auth/token HTTP/2.0", host: "gateway.example.com"

Reverse Proxy Architecture & Header Forwarding for Microservices / Gateway

Consolidating multiple backend microservices; such as a core REST API on port 8000, a dedicated authentication service on port 8001, and a real-time WebSocket gateway on port 8080; behind a single Nginx HTTPS domain (https://gateway.example.com) simplifies SSL certificate management, reduces DNS lookups, and gives frontend teams one unified API entry point.

The single biggest source of bugs in multi-service Nginx gateways is prefix-stripping behavior around trailing slashes. When you declare location /api/ with proxy_pass http://127.0.0.1:8000/; (trailing slash), Nginx strips /api/ so an incoming request to /api/orders arrives at port 8000 as /orders. Removing that single trailing slash (proxy_pass http://127.0.0.1:8000;) forwards /api/orders untouched; which immediately triggers 404s if your microservice expects /orders.

When combining subpath routing with Docker Compose service discovery (resolver 127.0.0.11 and set $upstream_endpoint), trailing slashes on proxy_pass no longer strip prefixes automatically. You MUST pair each service location block with an explicit rewrite ^/service/(.*)$ /$1 break; directive before proxy_pass $upstream_endpoint; so every microservice receives clean relative paths while still re-resolving container IPs dynamically.

Ordering and specificity of Nginx location blocks also matter: prefix locations with trailing slashes (like /api/) do NOT match bare /api without a trailing slash unless you handle /api or rely on Nginx's automatic slash normalization, and regex locations (~ or ~*) take precedence over standard prefix blocks unless you use the ^~ modifier.

Operating Nginx as a unified subpath API gateway for /api/, /auth/, and /ws/ microservices scales cleanly when you standardize shared proxy header snippets, isolate each service with location ^~ modifiers, and document Strip Prefix conventions per upstream team. Include $upstream_addr and $request_uri in Nginx gateway logs so on-call engineers can immediately trace whether a 404 originated from a missing trailing slash, a prefix rewrite mismatch, or an unhealthy downstream container; and test every subpath with curl after each gateway reload.

Step-by-Step Nginx & Microservices / Gateway Deployment Guide

Apply the Nginx server block above alongside these upstream framework trust-proxy settings so HTTPS detection, real client IPs, and reload safety work reliably in production.

  1. 1Define Isolated Subpath Location Blocks for Each Microservice

    /etc/nginx/sites-available/gateway.example.com.conf

    Split /api/, /auth/, and /ws/ into dedicated location blocks inside one HTTPS server block, setting custom timeouts and WebSocket upgrades only where needed.

    /etc/nginx/sites-available/gateway.example.com.confnginx
    location ^~ /api/ {
        resolver 127.0.0.11 valid=30s ipv6=off;
        set $api_upstream http://api_service:8000;
        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass $api_upstream;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    location ^~ /auth/ {
        resolver 127.0.0.11 valid=30s ipv6=off;
        set $auth_upstream http://auth_service:8001;
        rewrite ^/auth/(.*)$ /$1 break;
        proxy_pass $auth_upstream;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    location ^~ /ws/ {
        resolver 127.0.0.11 valid=30s ipv6=off;
        set $ws_upstream http://ws_service:8080;
        rewrite ^/ws/(.*)$ /$1 break;
        proxy_pass $ws_upstream;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 3600s;
    }
  2. 2Pass X-Forwarded-Prefix so Upstream Services Know Their Public Subpath

    /etc/nginx/snippets/proxy-common.conf

    Create a reusable proxy header snippet and add X-Forwarded-Prefix per location so upstream frameworks (Spring Boot, FastAPI, Laravel) can build accurate pagination and HATEOAS links even when prefixes are stripped.

    /etc/nginx/snippets/proxy-common.confnginx
    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 X-Forwarded-Host $host;
  3. 3Add a Clean JSON 404 Fallback for Unmatched Gateway Routes

    /etc/nginx/sites-available/gateway.example.com.conf

    Return a structured JSON 404 on location / so typos never leak default Nginx HTML error pages or attempt disk lookups under /etc/nginx/html/.

    /etc/nginx/sites-available/gateway.example.com.confnginx
    location / {
        default_type application/json;
        return 404 '{"error":"No upstream route matched at API gateway"}';
    }
  4. 4Verify Path Rewriting Across Every Subpath With curl

    terminal

    Reload Nginx and test each service prefix independently to verify status codes, forwarded headers, and stripped paths.

    terminalbash
    sudo nginx -t && sudo systemctl reload nginx
    curl -i https://gateway.example.com/api/health
    curl -i https://gateway.example.com/auth/health

Common Microservices / Gateway Nginx Reverse Proxy Pitfalls

Review these three production failure modes before reloading Nginx on staging or live servers.

Pitfall 1

Regex Location Blocks Stealing Static Assets Inside /api/ or /auth/

If your server block contains a regex location like location ~* \.(png|json|js)$ for static caching, Nginx evaluates regex locations BEFORE normal prefix locations; stealing /api/v1/schema.json away from your upstream. Prefixing with location ^~ /api/ stops regex overrides.

Pitfall 2

Relative Redirects Breaking When Upstream Strips Prefix

If an auth service behind /auth/ responds with Location: /login instead of /auth/login, browsers follow the redirect to https://gateway.example.com/login (404). Configure proxy_redirect / /auth/; in Nginx or configure a base path inside the upstream app.

Pitfall 3

Prefix Collisions Without Trailing Slashes (location /api Matching /api-v2)

Writing location /api (without a trailing slash) accidentally matches /api-v2 and /apidocs as well. Always include trailing slashes on subpath gateways (location ^~ /api/) to isolate routes cleanly.

Related Tools

Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:

Frequently Asked Questions

What is the exact difference between proxy_pass http://host:8000; and proxy_pass http://host:8000/;?
Omitting the trailing slash passes the complete original URI (/api/users -> /api/users). Appending the trailing slash replaces the matched location prefix with / (/api/users -> /users).
Why should I use location ^~ /api/ instead of plain location /api/?
The ^~ modifier tells Nginx to stop searching regex location rules once the prefix matches. This guarantees a global regex rule for .json or .svg files never accidentally hijacks an API endpoint.
How do I route /api (without trailing slash) cleanly to /api/?
Nginx automatically issues a 301 redirect from /api to /api/ when location /api/ uses proxy_pass. For POST requests (where 301 changes POST to GET), either call /api/ consistently from clients or add an exact location = /api block.
Can different subpaths have different client_max_body_size and timeouts?
Yes. Both client_max_body_size and proxy_read_timeout are valid inside individual location blocks; so you can keep /auth/ strict at 1M and 30s while giving /uploads/ 500M and 300s.
Browse all 10 Nginx guides →