Skip to content
Nginx

Rewrite & Redirect

Rewrite URIs and issue HTTP redirects.

#rewrite#redirect#url

Code

nginx
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;
}