basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Trailing slash in proxy_pass — strips the location prefix

    A single trailing / in proxy_pass http://127.0.0.1:3000/; makes nginx strip the matched location prefix from the request URI. Leave the slash off to pass the full path; put a trailing slash on both to strip the prefix.

    How nginx builds the upstream path

    If proxy_pass has no path after the host and port (http://127.0.0.1:3000), nginx forwards the original URI as is. If anything follows the port — even a single / (http://127.0.0.1:3000/ or http://127.0.0.1:3000/v2/) — nginx replaces the matched location prefix with that URI suffix (Reverse proxy).

    Before and after

    # Request /api/users reaches the app as /api/users
    location /api/ {
        proxy_pass http://127.0.0.1:3000;
    }
    
    # Request /api/users reaches the app as /users (/api/ prefix stripped)
    location /api/ {
        proxy_pass http://127.0.0.1:3000/;
    }

    Exception: when proxy_pass contains a variable (proxy_pass $upstream;), automatic prefix replacement turns off. Rewrite the path explicitly with rewrite ^/api/(.*)$ /$1 break; when you need it (Docker).

    If it doesn’t work

    The app receives /users instead of /api/users and returns 404

    Cause
    location /api/ has proxy_pass http://127.0.0.1:3000/; with a trailing slash, so nginx strips /api/.
    Fix
    Drop the trailing slash: proxy_pass http://127.0.0.1:3000;.

    Double slashes //users show up in the backend log

    Cause
    Mismatched trailing slashes: location /api (no /) with proxy_pass http://127.0.0.1:3000/; (with /).
    Fix
    Put a trailing slash on both: location /api/ and proxy_pass http://127.0.0.1:3000/;.