Nginx配置问题:将/status/ip请求重定向至http://ip:4444/status
解决Nginx路径参数提取与重定向/代理问题
问题分析
现有配置的核心错误:
- 错误通过
$args(URL查询参数)判断请求条件,而需求是从路径中提取IP参数 - 使用
$arg_param1获取查询参数值,完全不符合路径中提取IP的逻辑
解决方案
根据需求分两种场景给出配置:
场景1:客户端重定向(浏览器跳转至目标地址)
此方式会让客户端直接跳转到http://<ip>:4444/status,地址栏显示目标地址:
# 优先匹配带IP的路径请求 location ~ ^/status/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$ { # permanent 对应301永久重定向,redirect对应302临时重定向,按需选择 rewrite ^ http://$1:4444/status permanent; } # 处理其他/status/开头的请求,保留原有配置 location /status/ { proxy_pass http://ggr; add_header Access-Control-Allow-Origin '*' always; add_header Access-Control-Allow-Headers 'X-Requested-With,Content-Type' always; add_header Cross-Origin-Resource-Policy 'cross-origin' always; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 10; proxy_send_timeout 300; proxy_read_timeout 300; proxy_buffers 32 64m; proxy_buffer_size 64k; proxy_next_upstream error timeout http_502 http_503 http_504; client_max_body_size 64m; client_body_buffer_size 64m; }
场景2:Nginx反向代理(客户端地址不变,后台转发请求)
此方式下客户端始终访问localhost:3000/status/<ip>,由Nginx后台请求目标地址并返回响应:
# 优先匹配带IP的路径请求 location ~ ^/status/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$ { proxy_pass http://$1:4444/status; # 可选:设置目标地址的Host头 proxy_set_header Host $1:4444; proxy_http_version 1.1; proxy_set_header Connection ""; } # 处理其他/status/开头的请求,保留原有配置 location /status/ { proxy_pass http://ggr; add_header Access-Control-Allow-Origin '*' always; add_header Access-Control-Allow-Headers 'X-Requested-With,Content-Type' always; add_header Cross-Origin-Resource-Policy 'cross-origin' always; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 10; proxy_send_timeout 300; proxy_read_timeout 300; proxy_buffers 32 64m; proxy_buffer_size 64k; proxy_next_upstream error timeout http_502 http_503 http_504; client_max_body_size 64m; client_body_buffer_size 64m; }
关键说明
- 正则
^/status/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$精准匹配带IP的路径,捕获的IP存储在$1变量中 - 正则匹配的
location优先级高于前缀匹配的location /status/,因此带IP的请求会被优先处理
内容的提问来源于stack exchange,提问作者sachin
相关产品推荐
相关产品推荐

