permanent标记使rewrite指令返回http 301响应,自动设置location头并终止后续处理;常用于强制https、域名统一和路径调整,但推荐用return 301替代以提升可维护性与性能。

在 Nginx 中,使用 permanent 标记可让 rewrite 指令显式返回 HTTP 301(永久重定向)响应。
permanent 的作用和基本语法
permanent 是 rewrite 指令的可选标记之一,它会自动设置响应状态码为 301 Moved Permanently,并把重写后的新 URL 放入 Location 响应头中。语法格式如下:
rewrite permanent;
注意:该语句必须放在 server 或 location 块内;一旦匹配成功,Nginx 会立即终止当前请求处理流程,直接返回 301 响应,后续的 rewrite 或 proxy_pass 等指令不再执行。
常见使用场景示例
-
强制 HTTPS 访问:将所有 HTTP 请求永久跳转到 HTTPS 对应地址
rewrite ^(.*)$ https://$server_name$1 permanent; -
域名统一(如 www 跳非 www):
if ($host = 'www.example.com') {<br> rewrite ^(.*)$ https://example.com$1 permanent;<br>} -
路径结构调整:将旧路径
/old-page永久重定向到新路径/new-section/pagerewrite ^/old-page$ /new-section/page permanent;
注意事项与替代方案
permanent 虽简洁,但有几点需留意:
- 不支持在
if块外使用变量拼接(如$scheme、$host)时出错,建议用完整 URL(含协议)避免相对跳转问题 - 若只需临时跳转,改用
redirect(返回 302) - 更推荐用
return 301替代rewrite ... permanent,语义更清晰、性能略优,例如:return 301 https://example.com$request_uri;
用 permanent 实现 301 重定向简单直接,适合规则明确、无需复杂逻辑的场景;对可维护性和语义准确性要求较高时,优先考虑 return 301。











