如何在 Nginx 位置块中正确编写“或”语句?

Dav*_*ave 8 configuration nginx cache conditional

我在 CentOS 7 上使用 Nginx。我想为以特定扩展名结尾或在 URL 中包含“/image/”字符串的文件添加缓存控制标头。我试过这个

  location / {
    proxy_pass http://scale; # match the name of upstream directive which is defined above
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    if ($request_uri ~* ".(ico|gif|jpe?g|png)$") | ($request_uri ~* "/image/") {
      expires 60d;
      access_log off;
      add_header Pragma public;
      add_header Cache-Control "public";
      break;
    }
  }
Run Code Online (Sandbox Code Playgroud)

但重新启动服务器后,我得到了

invalid condition "$request_uri" in /etc/nginx/conf.d/scale.conf:16
Run Code Online (Sandbox Code Playgroud)

错误。如果我从有问题的行中删除“ | ($request_uri ~* “/image/”)”,一切都会重新启动,但随后我无法匹配我想要的东西。如何在配置文件中写入正确的 or 语句?

Bre*_*ith 6

在 nginx 中,if 是邪恶的。但如果你真的想这样做,你可以这样做:

if ($request_uri ~* "($\/image\/.*)|(.*\.(ico|gif|jpe?g|png)$)") {

本质上,只需组合正则表达式即可。