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
Server Block
Configure a virtual host with root, index, and try_files.
Reverse Proxy
Forward requests to upstream HTTP services.
Load Balancing
Distribute traffic across multiple upstream servers.
HTTPS & SSL
Terminate TLS with certificates and HTTP/2.
Location Rules
Match request URIs with prefix, regex, and exact locations.
Gzip Compression
Compress text responses to reduce bandwidth.