TExcelTAD

return, rewrite & Redirects

Sites move: http to https, www to the bare domain, /blog/2019/post to /posts/post, an old API version to a new one. Nginx has two tools for this. return answers immediately with a status and a URL or body; it is simple and fast. rewrite changes the URI with a regular expression and can either redirect the client or continue processing internally. Use return whenever you can.

Choosing the status code

Code Meaning Method on the next request Cached by browsers
301 Moved Permanently permanent may change POST to GET yes, often for a long time
302 Found temporary may change POST to GET no
307 Temporary Redirect temporary kept no
308 Permanent Redirect permanent kept yes

For page moves, 301 is fine. For APIs, where a client may POST to the old URL, use 308 or 307, or the body is lost on the way. Be careful with permanent redirects while testing: a browser that cached a wrong 301 keeps following it until its cache is cleared.

return

bash · try it yourself
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  access_log off;
  server {                                        # www -> bare domain, keeping path and query
    listen 127.0.0.1:8080;
    server_name www.shop.test;
    return 301 http://shop.test:8080$request_uri;
  }
  server {
    listen 127.0.0.1:8080;
    server_name shop.test;
    location = /old-pricing { return 301 /pricing; }       # relative: Nginx makes it absolute
    location /api/v1/       { return 308 /api/v2/; }        # keeps POST bodies; note: the rest of the path is dropped!
    location = /pricing     { return 200 "pricing page\n"; }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
r() { curl -s -o /dev/null -w "%{http_code} -> %{redirect_url}\n" -H "Host: $1" "127.0.0.1:8080$2" "${@:3}"; }
r www.shop.test "/cart?item=7"
r shop.test /old-pricing
r shop.test /api/v1/orders -X POST -d 'x=1'
echo "--- follow the chain with -L:"
curl -sL --resolve shop.test:8080:127.0.0.1 http://shop.test:8080/old-pricing
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
301 -> http://shop.test:8080/cart?item=7
301 -> http://shop.test:8080/pricing
308 -> http://shop.test:8080/api/v2/
--- follow the chain with -L:
pricing page

Two things to notice:

  • $request_uri is the original URI with the query string, exactly as the client sent it. $uri is the normalised path without the query string and may have been changed by rewrites; redirecting to $uri silently drops ?item=7.
  • return 308 /api/v2/; sent every /api/v1/… URL to /api/v2/, losing orders. To keep the rest of the path you need a capture, which is what rewrite (or a regex location) is for.

A relative target such as /pricing is turned into an absolute URL using the server's name and port (absolute_redirect on is the default; port_in_redirect and server_name_in_redirect control the details). Behind another proxy or a load balancer on a different port, that can produce redirects to the wrong port; absolute_redirect off; sends the relative Location: /pricing instead, which all current browsers accept.

rewrite and its flags

rewrite regex replacement [flag]; matches the regex against $uri. The flag decides what happens next:

Flag Effect
(none) keep processing the other rewrite directives in this block, then search for a location with the new URI
last stop this block's rewrites and search for a location again with the new URI
break stop rewrites and stay in the current location
redirect send a 302 to the client
permanent send a 301 to the client

If the replacement starts with http://, https:// or $scheme, it is always a redirect. The query string is appended automatically unless the replacement ends with ?.

bash · try it yourself
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  access_log off;
  default_type text/plain;
  server {
    listen 127.0.0.1:8080;
    rewrite ^/api/v1/(.*)$ /api/v2/$1 permanent;              # external: the client sees the new URL
    rewrite "^/blog/\d{4}/(.+)
quot; /posts/$1 last; # internal (quoted: the regex has { }): the client never sees /posts location /api/v2/ { return 200 "v2 handles $uri args=$args\n"; } location /posts/ { return 200 "post page for $uri (client asked for $request_uri)\n"; } } } EOF nginx -p "$PWD" -c nginx.conf -e stderr curl -s -o /dev/null -w "%{http_code} -> %{redirect_url}\n" "127.0.0.1:8080/api/v1/orders/9?expand=items" curl -s "127.0.0.1:8080/blog/2019/hello-world" nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
301 -> http://127.0.0.1:8080/api/v2/orders/9?expand=items
post page for /posts/hello-world (client asked for /blog/2019/hello-world)

A regex that contains { or } (like \d{4}) or ; must be quoted, otherwise Nginx reads the brace as the start of a block and nginx -t fails with directive "rewrite" is not terminated by ";". The permanent rewrite kept the path tail (orders/9) and the query string. The last rewrite happened entirely inside Nginx: the client asked for /blog/2019/hello-world and got the post with status 200, and $request_uri still shows what it asked for.

Rewrites at server level run before the location search; rewrites inside a location with last trigger a new search. Nginx stops after 10 internal redirects with a 500 and "rewrite or internal redirection cycle" in the error log, which is what a last rewrite that matches its own output produces.

About if

if exists in the rewrite module and works reliably for return and rewrite … last inside it. Other directives inside if in a location behave in surprising ways (the official wiki page is literally titled "If is Evil"). For choices based on headers or variables, compute a variable with map and use it in one simple if or directly in a directive.

nginx
# fine: return inside if
if ($http_x_forwarded_proto = "http") { return 308 https://$host$request_uri; }

Test yourself

An API moved from /v1/ to /v2/. Clients POST to the old URLs. Which status should the redirect use?

  1. 301
  2. 302
  3. 308
  4. 200

What is the difference between $request_uri and $uri?

  1. None
  2. $request_uri is the original URI with query string; $uri is the normalised, possibly rewritten path without it
  3. $uri includes the host
  4. $request_uri is lowercased

rewrite ^/blog/(.*)$ /posts/$1 last;: what does the client see?

  1. A 301 redirect to /posts/…
  2. Nothing changes for the client: Nginx searches for a location with the new URI internally
  3. A 302
  4. An error