NGINX位置正则表达式无法按预期工作

时间:2019-09-23 13:51:19

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

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

我尝试配置URL正则表达式,但是它似乎不起作用。以下是到目前为止的发现:

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;
    }

2 个答案:

答案 0 :(得分:0)

您可以这样做:

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

答案 1 :(得分:0)

尝试此配置:

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;
}