【问题标题】:NGINX location regex not working as per expectationNGINX 位置正则表达式未按预期工作
【发布时间】:2019-09-24 00:08:36
【问题描述】:

我正在尝试创建一个将流量重定向到特定端口的子 url。例如: 如果我的 URL 是 /a/status,它应该重定向到 127.0.0.1:8800/status。

我尝试配置 U​​RL 正则表达式,但它似乎不起作用。以下是目前的调查结果:

location /
    {
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header Access-Control-Allow-Origin *;
        proxy_pass http://127.0.0.1:8800;
        include /etc/nginx/proxy_params;
    }

对于上述代码,URL /status 将流量正确重定向到 8800 端口。但是,使用下面的代码,存在问题。

location /a/
    {
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header Access-Control-Allow-Origin *;
        proxy_pass http://127.0.0.1:8800;
        include /etc/nginx/proxy_params;
    }

URL /a/status,不会重定向到端口 8800。我也尝试使用下面代码的正则表达式,但没有成功:

location ~* ^/(.+)/$
    {
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header Access-Control-Allow-Origin *;
        proxy_pass http://127.0.0.1:8787;
        include /etc/nginx/proxy_params;
    }

【问题讨论】:

    标签: nginx nginx-location nginx-reverse-proxy


    【解决方案1】:

    你可以这样做:

    server {
      listen 80;
      server_name test.com;
    
      # considering /a/status
      # if you want to for any prefix go with "location ~ \/(.+)\/status"
      location = /a/status {
        # there are ways to dynamically rewrite depending on prefix, comment if that part is needed as well
        rewrite ^ /status last;
      }
    
      location = /status {
        proxy_pass http://127.0.0.1:8800; 
      }
    }
    
    server {
      listen 8800;
      location / {
        return 201;
      }
    }
    

    当我们卷曲它时,我们看到它转到 8800 服务器:

    # curl -I localhost/a/status -H "host: test.com"
    HTTP/1.1 201 Created
    Server: nginx/1.12.2
    Date: Mon, 23 Sep 2019 14:08:53 GMT
    Content-Type: application/octet-stream
    Content-Length: 0
    Connection: keep-alive
    

    【讨论】:

      【解决方案2】:

      试试这个配置:

      location ^~ /a/status {
          add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If- 
          Modified-Since,Cache-Control,Content-Type,Range';
          add_header Access-Control-Allow-Origin *;
          proxy_pass http://127.0.0.1:8800;
          include /etc/nginx/proxy_params;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-04-28
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多