【问题标题】:Nginx using the wrong location blockNginx 使用了错误的位置块
【发布时间】:2022-01-17 07:33:08
【问题描述】:

我有以下 nginx 配置:

upstream front {
    server localhost:4000;
}
upstream back {
    server localhost:8000;
}

server {
  server_name my_domain.com;
  listen 80;

  location ~ /api($|/.*) {
    rewrite ^/api($|/.*) /VirtualHostBase/http/my_domain.com:80/Intk/VirtualHostRoot/_vh_api$1 break;
    proxy_pass http://back;
  }

  location ~ / {
    add_header Cache-Control "public";
    expires +1m;
    proxy_pass http://front;
  }

  location ~ /orgs/.+$ {
    return 301 http://my_domain.com/orgs;
  }

  location ~* manage_ {
    deny all;
  }

  location ~ \.php$ {
    return 410;
    access_log off;
  }

  location ~ ^/(wp-admin|wp-content) {
    return 410;
    access_log off;
  }

  location = /nginx_stub_status {
    stub_status on;
    allow 127.0.0.1;
    deny all;
  }

}

server {
  server_name www.my_domain.com;
  listen 80;
  access_log off;
  return 301 http://my_domain.com$request_uri;
}

我不明白它有什么问题,特别是第三个位置块。 如果我写my_domain.com/orgs/some-org,它不应该重定向到my_domain.org/orgs吗? 它没有那样做,它就像那个位置块不存在一样。

据我了解,nginx 应该以最具体的匹配来满足请求,它应该是第三个位置块中的那个。

【问题讨论】:

    标签: nginx redirect


    【解决方案1】:

    http://example.com/orgs 将匹配 location ~ / {} 而不是 location ~ /orgs/.+$ {}。考虑将rewrite 放在位置块之外,并使用location / {}(没有~ 的非正则表达式)作为您的后备。

    server {
      rewrite ~ ^/orgs/.+ /orgs permanent;
    
      # fallback
      location / {
      }
    }
    

    【讨论】:

    • 我知道我的请求与location ~ / {} 匹配,但为什么呢? nginx 不应该使用最具体的匹配吗?为什么不是location ~ /orgs/.+$ {}
    • 很遗憾,我没有答案。我通常会使用各种配置进行大量测试,直到一切正常。
    猜你喜欢
    • 2018-02-01
    • 1970-01-01
    • 2011-12-23
    • 2020-07-06
    • 2013-04-21
    • 2016-01-09
    • 2017-06-16
    • 2014-12-18
    • 2013-12-21
    相关资源
    最近更新 更多