Return vs Rewrite
Return (Preferred for Redirects)
# Simple redirects - use return
server {
listen 80;
server_name example.com;
return 301 https://example.com$request_uri;
}
# Return codes
return 301 https://...; # Permanent redirect
return 302 https://...; # Temporary redirect
return 307 https://...; # Temporary, preserve method
return 308 https://...; # Permanent, preserve method
return 404; # Not found
return 444; # Close connection
Rewrite (For Complex Patterns)
# Rewrite syntax: rewrite regex replacement [flag];
location / {
rewrite ^/old-page$ /new-page permanent;
rewrite ^/user/(.*)$ /profile/$1 last;
}
Rewrite Flags
| Flag |
Description |
| last |
Stop processing and restart location search |
| break |
Stop processing, use current location |
| redirect |
302 temporary redirect |
| permanent |
301 permanent redirect |
Common Redirect Patterns
HTTP to HTTPS
server {
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
WWW to Non-WWW
server {
listen 443 ssl;
server_name www.example.com;
return 301 https://example.com$request_uri;
}
Non-WWW to WWW
server {
listen 443 ssl;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
Trailing Slash
# Add trailing slash
rewrite ^([^.]*[^/])$ $1/ permanent;
# Remove trailing slash
rewrite ^/(.*)/$ /$1 permanent;
Rewrite Examples
Path Changes
# Old blog URL to new
rewrite ^/blog/([0-9]+)/([0-9]+)/(.*)$ /posts/$3 permanent;
# Remove .html extension
rewrite ^(.+)\.html$ $1 permanent;
# Add .php extension
location / {
try_files $uri $uri/ @php;
}
location @php {
rewrite ^(.*)$ $1.php last;
}
Query String Handling
# Redirect with query string
rewrite ^/search$ /find?$args redirect;
# Ignore query string
rewrite ^/page$ /newpage? permanent;
# Change query parameter
if ($args ~* "^id=(.*)") {
set $id $1;
rewrite ^/product$ /item/$id? permanent;
}
Conditional Rewrites
# Rewrite based on user agent
if ($http_user_agent ~* "mobile") {
rewrite ^(.*)$ /mobile$1 last;
}
# Rewrite based on cookie
if ($http_cookie ~* "beta=1") {
rewrite ^(.*)$ /beta$1 last;
}
try_files (Preferred Over Rewrite)
# Try file, directory, then fallback
location / {
try_files $uri $uri/ /index.html;
}
# Try file, then named location
location / {
try_files $uri @backend;
}
location @backend {
proxy_pass http://app;
}
Error Page Redirects
# Custom error pages
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
# Redirect to external page on error
error_page 404 = @handle_404;
location @handle_404 {
return 302 /not-found;
}
intermediate | Core Concepts | Updated 2025-01-15
- nginx
- rewrite
- redirect
- url
- regex