如何使用NGINX重定向含双斜杠的404外部反向链接?
解决NGINX中双斜杠URL的重定向问题
问题背景
有一条指向本站的外部反向链接因URL包含双斜杠,访问时返回404错误:
- 错误路径:
/en//effective-link-prospecting-with-marketing-miner-in-4-steps.html - 正确目标路径:
/en/blog/effective-link-prospecting-with-marketing-miner-in-4-steps.html
尝试以下NGINX规则但未生效:
rewrite ^/en//effective-link-prospecting-with-marketing-miner-in-4-steps.html https://www.marketingminer.com/en/blog/effective-link-prospecting-with-marketing-miner-in-4-steps.html permanent;
原因分析
NGINX默认会自动将URL中的多个连续斜杠合并为单个斜杠,因此实际处理请求时,路径会被转换为/en/effective-link-prospecting-with-marketing-miner-in-4-steps.html,导致带双斜杠的匹配规则无法命中请求。
解决方案
方案一:匹配合并后的单斜杠路径(推荐)
直接针对合并后的标准路径编写重定向规则,无论原始请求是双斜杠还是多斜杠,都会被NGINX统一处理后匹配:
rewrite ^/en/effective-link-prospecting-with-marketing-miner-in-4-steps.html$ https://www.marketingminer.com/en/blog/effective-link-prospecting-with-marketing-miner-in-4-steps.html permanent;
方案二:关闭NGINX的斜杠合并功能(不推荐)
如果必须严格匹配原始双斜杠路径,可以通过merge_slashes off;关闭自动合并,但这种做法可能引入安全风险(比如路径遍历类漏洞的潜在风险),仅在特殊场景下使用:
server { merge_slashes off; rewrite ^/en//effective-link-prospecting-with-marketing-miner-in-4-steps.html$ https://www.marketingminer.com/en/blog/effective-link-prospecting-with-marketing-miner-in-4-steps.html permanent; # 其他服务器配置... }
内容的提问来源于stack exchange,提问作者Forlis
相关产品推荐
相关产品推荐

