You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx合并相似location指令后无法正常工作的问题求助

解决Nginx合并location指令的问题

你的合并代码问题出在正则捕获组的引用错误:rewrite ^/(recipes|media/recipes)/(.*) /$1 break; 中的$1匹配的是recipes或media/recipes这个前缀,而非后面的文件名,导致最终代理路径变成https://$s3_bucket/media/recipes/recipes/potatoes.pdf或https://$s3_bucket/media/recipes/media/recipes/potatoes.pdf,自然无法访问。

下面是两种正确的合并方案:

方案一:调整捕获组引用(保留rewrite)

把第一个捕获组设为非捕获(用?:),让$1直接指向文件名部分:

location ~ ^/(?:recipes|media/recipes)/ {
  rewrite ^/(?:recipes|media/recipes)/(.*)$ /$1 break;
  proxy_pass https://$s3_bucket/media/recipes/$1;
}

方案二:省略rewrite,直接用location正则捕获

利用location本身的正则匹配捕获文件名,无需额外rewrite,更简洁高效:

location ~ ^/(?:recipes|media/recipes)/(.*)$ {
  proxy_pass https://$s3_bucket/media/recipes/$1;
}

这两种方案都能正确处理example.com/recipes/potatoes.pdf和example.com/media/recipes/potatoes.pdf,将它们代理到https://$s3_bucket/media/recipes/potatoes.pdf。

内容的提问来源于stack exchange,提问作者Hagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:02:11