【问题标题】:nginx location with and without trailing slash带有和不带有斜杠的 nginx 位置
【发布时间】:2018-11-23 11:06:55
【问题描述】:

我想创建一个可以同时捕获http://example.comhttp://example.com/ 的位置,以及另一个可以捕获其他所有内容的位置。第一个将提供静态 html,另一个用于 api 和其他内容。我试过这个:

location ~ /?$ {
    root /var/www/prod/client/www;
}

location ~ /.+ {
    # https://stackoverflow.com/questions/21662940/nginx-proxy-pass-cannot-have-uri-part-in-location
    rewrite ^/(.*) /$1 break;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_connect_timeout       1s;
    proxy_send_timeout          30s;
    proxy_read_timeout          300s;
    send_timeout                300s;

    proxy_redirect off;
    proxy_pass http://backendPro;
}

但不起作用。我在第一个位置尝试了很多选项,但是当它首先匹配时,第二个不匹配,反之亦然:

location / {
location ~ \/?$ {
location ~ ^/?$ {

【问题讨论】:

    标签: nginx nginx-location


    【解决方案1】:

    实际上要简单得多:

    location = / {
      # Exact domain match, with or without slash
    }
    
    location / {
      # Everything except exact domain match
    }
    

    因为location = /更具体,所以如果只调用域名总是首选(位置块的顺序无关紧要)。

    您在 Nginx 中需要的正则表达式比您想象的要少得多,因为正常的位置块匹配每个匹配开头的 URL,所以 location /bla 匹配域中以 /bla 开头的每个 URL(如 /blabla 或 /bla /blu 或 /bla.jpg)。如果您需要捕获组并对其进行处理,我主要推荐使用正则表达式。

    【讨论】:

      猜你喜欢
      • 2012-12-14
      • 2017-06-15
      • 2018-12-07
      • 1970-01-01
      • 2019-04-09
      • 2020-11-04
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多