Skip to content
Nginx

Rewrite & Redirect

Rewrite URIs and issue HTTP redirects.

By EZ4Code Team
rewriteredirecturl

Code

server {
    listen 80;
    server_name example.com;

    # Permanent redirect (301)
    rewrite ^/old/(.*)$ https://$host/new/$1 permanent;

    # Internal rewrite (no client redirect)
    rewrite ^/download/(.*)$ /files/$1 last;

    # Capture groups
    location ~ ^/u/(\w+)$ {
        return 301 /users/$1/profile;
    }

    # Conditional redirect based on host
    if ($host = 'old.example.com') {
        return 301 https://example.com$request_uri;
    }

    # Strip trailing slash
    rewrite ^/(.*)/$ /$1 permanent;
}

Explanation

rewrite changes the request URI before processing continues; 'last' re-runs location matching while 'break' stops rewrite processing. return issues an HTTP redirect directly, which is faster and clearer for simple cases. Avoid 'if' for complex logic—prefer map or separate server blocks.

More Nginx Snippets