Beginner Fundamentals

Rewrite Rules

The rewrite directive changes a request URI using a regular expression. It is more powerful than return and is used for pattern-based URL changes.

Basic Syntax

rewrite regex replacement [flag];

The regex matches the incoming URI, and the replacement builds the new one. Captured groups become $1, $2, and so on:

rewrite ^/blog/(\d+)$ /posts/$1 last;

A request for /blog/42 becomes /posts/42.

The Flags

Flags control what happens after the rewrite:

  • last: stop processing rewrites and search for a new matching location.
  • break: stop rewrites and stay in the current location.
  • redirect: send a 302 temporary redirect to the client.
  • permanent: send a 301 permanent redirect to the client.
rewrite ^/promo$ /campaign permanent;

This visibly redirects the browser with a 301.

last vs break

last re-runs location matching with the new URI, while break keeps the request in place. Use break when you do not want the rewrite to loop back through other location blocks.

location /files/ {
    rewrite ^/files/(.*)$ /storage/$1 break;
    root /var/www;
}

A Word of Caution

Rewrites run on every matching request and can be hard to debug. For simple moves prefer return. Reach for rewrite only when you truly need regex capture and replacement.