Nginx 重定向配置:rewrite
固定跳转优先使用 return;只有需要复杂条件或内部重写时才使用 rewrite,避免难维护的正则链。
固定重定向
server {
listen 80;
server_name old.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 80;
server_name example.com;
location = /old {
return 302 /new;
}
}内部重写
location /download/ {
rewrite ^/download/(.*)$ /files/$1 last;
}
location /legacy/ {
rewrite ^/legacy/(.*)$ /app/$1 break;
proxy_pass http://127.0.0.1:3000;
}last 与 break
last:停止当前规则并重新进行 location 匹配。break:停止当前规则,继续在当前 location 内处理。- 外部固定跳转使用
return 301/302,比 rewrite 更直观。