rewrite 与 return
约 560 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Nginx › 高级配置(在新窗口打开) › rewrite 与 return
return
return 是最简单的响应控制指令,用于返回状态码和内容。
# 301 永久重定向
location /old-page {
return 301 /new-page;
}
location /old-path/ {
return 301 https://$host/new-path/$uri;
}
# 307 临时重定向(保留请求方法)
location /temp-redirect {
return 307 /new-location;
}
# 返回状态码和响应体
location /health {
return 200 "OK\n";
}
# 返回 403/404
location /admin {
return 403;
}
location /deleted {
return 404;
}rewrite
rewrite 使用正则修改 URI,可以多次执行(最多 10 次)。
rewrite regex replacement [flag];| flag | 含义 |
|---|---|
last | 完成重写后重新搜索 location |
break | 完成重写后停止(不重新搜索 location) |
redirect | 返回 302 临时重定向 |
permanent | 返回 301 永久重定向 |
last vs break
server {
rewrite ^/old/(.*)$ /new/$1 last; # 重写后重新匹配 location
# ^^^^ 去重写后的 /new/xxx 匹配 location
location /new/ {
return 200 "New location";
}
}
location /example {
rewrite ^/example /redirect last; # 重新搜索 location
# 实际不会执行到这里(last 跳出了当前 location)
}redirect 与 permanent
# 返回 302(临时)
rewrite ^/page-(\d+)$ /articles?id=$1 redirect;
# 返回 301(永久,SEO)
rewrite ^/page-(\d+)$ /articles?id=$1 permanent;if 的使用(谨慎)
Nginx 的 if 有诸多陷阱,只在极少数场景推荐使用。
推荐用法
# 检查文件是否存在
if (!-f $request_filename) {
rewrite ^ /index.html last;
}
# 根据 User-Agent 拒绝
if ($http_user_agent ~* (cur|bot|scanner)) {
return 403;
}不推荐用法
# ❌ 不推荐:if 内放 proxy_pass
if ($scheme = http) {
rewrite ^ https://$host$request_uri permanent;
}
# ✅ 推荐:用两个 server 块
server {
listen 80;
return 301 https://$host$request_uri;
}实际场景
强制 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}添加/去除 URL 后缀
# PHP 伪静态
location / {
try_files $uri $uri/ @php;
}
location @php {
rewrite ^/(.*)$ /index.php?q=$1 last;
}Canonical 域名
server {
listen 80;
server_name www.example.com;
return 301 https://example.com$request_uri;
}维护模式
location / {
if (-f /var/www/maintenance.html) {
return 503;
}
# 正常处理
}小结
return比rewrite更简单高效,适合重定向和状态码响应。rewrite在 server/location 上下文中重写 URI,last/break控制是否重新匹配 location。redirect(302)和permanent(301)标志对外部客户端重定向。if在 Nginx 中行为复杂,尽量避免在其中放入 proxy_pass 等指令。- HTTPS 跳转推荐用两个
server块 +return 301。
上一节:HTTP/2 与 HSTS 下一节:gzip 压缩
