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
相关产品推荐
相关产品推荐

