NGINX location regex未按预期工作
我试图创建一个子url,将流量重定向到特定端口。例如: 如果我的URL是/a/status,它应该重定向到127.0.0.1:8800/status 我试图配置URL正则表达式,但它似乎不起作用。以下是迄今为止的调查结果:NGINX location regex未按预期工作,nginx,nginx-location,nginx-reverse-proxy,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,Conten
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/状态不会重定向到端口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;
}
您可以这样做:
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
请尝试以下配置:
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;
}