basforge

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

    RU
    ConfigHomelabnginx

    Redirects, rewrite, and subpath proxying in nginx: 301/308, map, and proxy_redirect

    Working configs for redirects and proxying services under /app/: choosing between 301/302 and 308/307, bulk URL migrations with map, return vs rewrite, and combining proxy_redirect, proxy_cookie_path, and sub_filter.

    Redirect codes: why 301 breaks APIs while 308 doesn’t

    The four redirect status codes differ along two axes: browser caching and whether POST keeps its method and body.

    Code Lifetime POST method and body When to use
    301 Permanent (cached by browsers) Clients often switch to GET Moving web pages and domains (http to https, www to apex)
    302 Temporary Clients often switch to GET Temporary maintenance, A/B tests, testing rules before enabling 301
    307 Temporary Preserved unchanged Temporarily moving an API endpoint or webhook
    308 Permanent (cached by browsers) Preserved unchanged Permanently moving an API route receiving POST/PUT/PATCH

    Start with 302 (or 307) while wiring and verifying rules so a mistake is reversible in one config edit. Ship a broken 301, and visitors’ browsers will keep following the wrong target even after you fix nginx.

    return vs rewrite

    return stops processing immediately and sends the response without evaluating regular expressions — use it for 90% of redirects: domain moves, page moves, and map-driven redirect tables.

    Reach for rewrite in two cases: rewriting a URI internally inside nginx without telling the browser, or assembling a target URL from regex capture groups. Its trailing flag controls what happens next:

    rewrite flag Behavior
    break Updates $uri and stays in the current location, passing the new path to proxy_pass or root
    last Updates $uri and restarts location lookup with the new path (up to 10 jumps, then 500)
    redirect Sends an external 302 redirect to the browser
    permanent Sends an external 301 redirect to the browser

    Inside a location with proxy_pass on regex paths (when the trailing-slash rule in Trailing slash in proxy_pass doesn’t fit), use break: rewrite ^/legacy/(.*)$ /$1 break;.

    Setup 1: bulk URL migration with map and API moves with 308

    When a site restructure leaves dozens or hundreds of old URLs to forward, don’t pile up location blocks or if chains. Put the mapping in an http-level map: nginx looks up exact strings in a hash table in constant time and falls back to regex entries only when no exact match hits.

    /etc/nginx/conf.d/02-redirects-map.conf
    map $uri $redirect_target {
        default             "";
        /old-pricing        /pricing;
        /docs/v1/install    /docs/v2/install;
        ~^/blog/([0-9]+)$   /posts/$1;
    }
    Key part

    Table of old and new paths. Exact entries (/old-pricing) resolve instantly by hash; ~ entries run as regexes with capture groups ($1). Unmatched URLs leave $redirect_target empty.

    Wire the table into server, alongside a 308 API move:

    /etc/nginx/conf.d/redirects.example.org.conf
    server {
        listen 443 ssl;
        http2 on;
        server_name example.org;
    
        # ssl_certificate / ssl_certificate_key / snippets/tls.conf
    
        if ($redirect_target) {
            return 301 $redirect_target$is_args$args;
        }
    Key part

    One check in server: if $redirect_target is non-empty, return 301 while preserving query parameters ($is_args$args appends ?plan=pro only when query args exist). An if containing only return is safe (if inside location).

        location /v1/webhook {
            return 308 /v2/webhook$is_args$args;
        }
    
        location /v2/webhook {
            include snippets/proxy-headers.conf;
            proxy_pass http://127.0.0.1:3000;
        }
    }

    API or webhook move: 308 keeps the POST method and JSON body. With 301, a payment gateway or HTTP client would downgrade POST to an empty GET.

    Setup 2: proxying an app under a /app/ subpath

    A common home-server layout puts Grafana, an admin UI, or an internal tool at https://example.org/app/ instead of a dedicated subdomain. If the app supports a base path setting (Base URL, Root URL, GF_SERVER_ROOT_URL), set it there first — that prevents half the broken-link bugs on its own.

    When the app lacks that option or still emits root-relative redirects and cookies for /, nginx needs four pieces: paired trailing slashes, proxy_redirect, proxy_cookie_path, and (as a last resort) sub_filter.

    /etc/nginx/conf.d/subpath.example.org.conf
        location = /app {
            return 301 /app/;
        }

    Exact match location = /app redirects to /app/ with a trailing slash. Without it, browsers resolve relative links like style.css against / (/style.css) instead of /app/style.css.

        location /app/ {
            include snippets/proxy-headers.conf;
            proxy_set_header Connection "";
            proxy_set_header X-Forwarded-Prefix /app;
    
            proxy_pass http://127.0.0.1:4000/;
            proxy_redirect / /app/;
            proxy_cookie_path / /app/;
    Key part

    Paired trailing slashes on location /app/ and proxy_pass http://127.0.0.1:4000/; strip /app/ before forwarding to the backend (Trailing slash in proxy_pass). X-Forwarded-Prefix tells aware frameworks their external mount point. proxy_redirect / /app/; rewrites backend Location: /login headers to /app/login, and proxy_cookie_path / /app/; scopes cookies to /app/ so sessions from sibling apps on the same domain don’t collide.

    default:proxy_redirect defaultproxy_cookie_path off

            proxy_set_header Accept-Encoding "";
            sub_filter 'href="/' 'href="/app/';
            sub_filter 'src="/'  'src="/app/';
            sub_filter_once off;
        }

    Last resort when HTML hardcodes root-relative paths (href="/static/...") and the app has no Base URL setting. ngx_http_sub_module is compiled into the nginx.org package. proxy_set_header Accept-Encoding ""; is required: if the backend gzips the HTML, sub_filter skips it silently. Drop these four lines if the app supports Base URL natively.

    default:sub_filter_once onsub_filter_types text/html

    How to check

    1. Validate syntax and reload:
      sudo nginx -t && sudo systemctl reload nginx
    2. Verify the map redirect table preserves query strings and regex captures:
      curl -sS -I "https://example.org/old-pricing?plan=pro" | grep -iE '^(HTTP/|location:)'
      # HTTP/2 301
      # location: https://example.org/pricing?plan=pro
      
      curl -sS -I "https://example.org/blog/42" | grep -iE '^(HTTP/|location:)'
      # HTTP/2 301
      # location: https://example.org/posts/42
    3. Verify 308 keeps the POST method and body (follow the redirect with -L and pass data with -d, without -X POST):
      curl -sS -i -L -d "event=ping" https://example.org/v1/webhook
      # HTTP/2 308
      # location: https://example.org/v2/webhook
      # HTTP/2 200
      # POST path=/v2/webhook body=event=ping
    4. Verify proxy_redirect and proxy_cookie_path under /app/:
      curl -sS -I https://example.org/app/old-login | grep -iE '^(HTTP/|location:|set-cookie:)'
      # HTTP/2 302
      # location: https://example.org/app/login
      # set-cookie: sid=abc123; Path=/app/; HttpOnly
    5. Verify sub_filter when the client requests compression — links in HTML should carry the /app/ prefix:
      curl -sS -H "Accept-Encoding: gzip" --compressed https://example.org/app/page
      # <a href="/app/static/app.css">css</a> <script src="/app/static/app.js"></script>

    If it doesn’t work

    After a 301 redirect to a new API URL, webhooks and POST requests arrive at the backend as empty GET requests

    Cause
    For historical reasons, browsers and HTTP clients turn POST into GET and drop the request body on 301 and 302.
    Fix
    Use return 308 (permanent) or return 307 (temporary) for APIs, forms, and webhooks — both preserve the original HTTP method and body.

    You fixed a redirect and reloaded nginx, yet the browser still jumps to the old target

    Cause
    Browsers cache 301 and 308 redirects aggressively and skip contacting the server on repeat visits.
    Fix
    Test with curl -sI (it never caches redirects). Use 302/307 while testing and switch to 301/308 once verified; clear the browser cache via DevTools (Disable cache).

    An app hosted at example.org/app/ redirects to example.org/login after sign-in and hits 404

    Cause
    The backend doesn’t know about the /app/ prefix and returns Location: /login, which nginx forwards unchanged.
    Fix
    Add proxy_redirect / /app/; inside location /app/ so nginx rewrites root-relative Location headers from the backend.

    You added sub_filter to rewrite HTML links, yet nothing on the page changed

    Cause
    The backend returned a gzip-compressed body, and ngx_http_sub_module only processes uncompressed text — it silently skips compressed responses.
    Fix
    Disable upstream compression with proxy_set_header Accept-Encoding ""; (nginx still compresses the response sent to the browser).

    A rewrite inside location entered an infinite loop and failed with 500 Internal Server Error (rewrite or internal redirection cycle)

    Cause
    With the last flag, nginx restarts location matching after rewriting the URI, hits the same block again, and aborts after 10 cycles.
    Fix
    If you want to stay in the current location and pass the rewritten path straight to proxy_pass or root, switch last to break.

    Behind an external proxy or on a non-standard port, nginx puts an internal port in Location, like http://example.org:8080/app/

    Cause
    By default absolute_redirect on and port_in_redirect on make nginx build a full Location URL with its own local scheme and port.
    Fix
    Set absolute_redirect off; (nginx returns a relative Location: /app/) or port_in_redirect off;.