使用 rewrite ... permanent 可实现 nginx 的 301 永久重定向,语法为 rewrite 正则表达式 替换目标 permanent;,需置于 server 或 location 块中,nginx 自动补全协议和域名生成绝对 url。

在 Nginx 中,使用 permanent 标志位是配置 301 永久重定向最简洁的方式,它会自动将状态码设为 301 Moved Permanently,并把重定向 URL 构建为绝对地址(含协议、域名和路径)。
如何用 rewrite ... permanent 实现 301 重定向
语法格式为:
rewrite 正则表达式 替换目标 permanent;该指令必须放在 server 或 location 块中。Nginx 会自动补全 scheme 和 host,生成完整跳转地址。
- 若当前请求是
https://example.com/old,且配置了rewrite ^/old$ /new permanent;,浏览器将收到Location: https://example.com/new - 目标路径支持变量,如
$request_uri、$host,但通常直接写路径更安全 - 注意:正则匹配失败时,该 rewrite 不生效,不会导致错误
与 return 301 的区别
return 301 更底层、更可控,适合简单跳转;rewrite ... permanent 适合需要正则匹配和路径重写的场景。
-
return 301 https://example.com/new;—— 直接返回,不经过重写引擎,性能略高 -
rewrite ^/blog/(.*)$ https://blog.example.com/$1 permanent;—— 利用正则捕获并拼接,适合结构化迁移 -
permanent本质是rewrite ... redirect的快捷方式,等价于rewrite ... redirect+ 状态码隐式设为 301
常见注意事项
实际配置中容易忽略几个关键点:
- 确保目标 URL 是完整 URL(含
http://或https://),否则 Nginx 默认按相对路径处理,可能产生意外跳转 - 避免循环重定向:检查 rewrite 规则是否可能再次匹配自身(例如未加锚点
^和$) - 若在
location块中使用,注意 location 匹配优先级;建议对纯跳转需求优先考虑return 301,语义更清晰 - 修改后务必执行
nginx -t测试配置,并nginx -s reload生效











