Nginx 中应优先用 return 301 实现精准路径跳转,如 location = /old-page.html { return 301 /new-page; },避免 rewrite 引发的循环或临时跳转问题;404 跳转需通过 error_page 404 = @notfound 配合命名 location 实现;注意 $host 安全性,禁用开放重定向。

在 Nginx 中,location 块适合处理**精确路径跳转、单页迁移或条件性重定向**,但不是全站 HTTP→HTTPS 或域名统一的首选方式。它必须配合 = 精确匹配或正则谨慎使用,否则容易被覆盖、失效或引发循环。
用 return 301 实现精准路径跳转
这是最轻量、最可靠的做法。Nginx 不走正则、不进 location 匹配链,直接返回响应,开销小且行为确定。
- 跳转单个页面:比如把
/old-page.html永久移到/new-page - 写法是:
location = /old-page.html { return 301 /new-page; } -
=表示严格等于,避免误匹配/old-page.html?abc或/old-page.html/sub - 目标地址可写绝对 URL(如
https://example.com/new-page),也可写相对路径(如/new-page),后者会继承当前协议、主机和端口
避免在 location 里用 rewrite 做 301
rewrite 在 location 中默认返回 302,除非显式加 permanent;且易受其他规则干扰,调试困难。
- 错误写法:
rewrite ^/old(.*)$ /new$1;→ 返回 302(临时跳转) - 勉强可用但不推荐:
rewrite ^/old(.*)$ /new$1 permanent; - 问题:若该 location 被多个 rewrite 或 if 块嵌套,可能触发内部重定向循环,日志报
rewrite or internal redirection cycle - 更稳妥的方式始终是用
return 301
处理 404 后自动跳转需命名 location 中转
不能直接在 error_page 404 后写 return,Nginx 语法不允许。必须借助命名 location。
- 正确结构:
error_page 404 = @notfound;location @notfound { return 301 https://example.com/; }-
=是关键,表示“以该命名 location 的响应体作为最终响应”,而不是内部重定向 - 如果漏掉
=,Nginx 会尝试返回@notfound对应的 URI,可能造成 404 嵌套或跳转失败
注意 $host 和 $request_uri 的安全使用
在 location 内引用变量时,尤其涉及跳转目标,要防范开放重定向风险。
- 不建议直接写:
return 301 https://$host$request_uri;(当 Host 头异常或 IP 直连时,$host 可能为空或不可信) - 更安全做法是限定域名:
if ($host = "a.com") { return 301 https://www.a.com$request_uri; } - 或拆分为独立 server 块处理不同域名,让 location 专注路径逻辑
- $request_uri 保留原始路径和查询参数,一般没问题;但若需清理参数,得用 rewrite + break,不推荐在简单跳转中引入复杂逻辑


















