nginx 将相似的位置指令合并为一个

hof1towb  于 2023-04-29  发布在  Nginx
关注(0)|答案(1)|浏览(198)

我想把这两个指令合并成一个,以避免冗余。他们俩都在工作。示例URL是:example.com/recipes/potatoes.pdfexample.com/media/recipes/potatoes.pdf

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

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

当我把它们像这样组合起来:

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

它根本不工作,但不会抛出任何错误。我假设文件名没有正确匹配,但我找不到错误。proxy_pass https://$s3_bucket/media/recipes/$1;需要纯文件名i。e. proxy_pass https://$s3_bucket/media/recipes/potatoes.pdf;
谢谢!

vhipe2zx

vhipe2zx1#

在“组合”尝试中,您在重写regexp中引入了第二个捕获组。因此,您还需要更改引用:

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

或者,您可以只捕获部分,并合并更多。
我会选择:

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

相关问题