Nginx配置问题:如何让含/protected/的请求先过认证再路由
问题原因
Nginx的location匹配遵循精确匹配(=)>最长前缀匹配>正则匹配的优先级规则,你配置的/protected/application1、/protected/application2属于更长的前缀匹配,会优先被命中,完全跳过了/protected/块中的auth_request认证逻辑,导致子路径无需认证即可访问。
解决方案
以下两种方案都可以解决问题,根据你的实际场景选择:
方案一:抽离认证逻辑复用(适合子路径较少的场景)
把认证相关的指令单独抽成一个配置片段,在所有需要认证的location中引入,避免重复代码:
- 创建认证配置片段(比如
/etc/nginx/snippets/auth-protected.conf):
auth_request /auth; auth_request_set $auth_status $upstream_status; proxy_set_header X-Real-IP $remote_addr;
- 修改原有Nginx配置:
location /protected/application1 { include snippets/auth-protected.conf; proxy_pass http://localhost:4501; } location /protected/application2 { include snippets/auth-protected.conf; proxy_pass http://localhost:4502; } location /protected/ { include snippets/auth-protected.conf; proxy_pass http://localhost:4500; } location = /auth { internal; proxy_pass http://localhost:8081/welcome; proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; }
方案二:用正则+Map统一处理(适合子路径较多的场景)
通过正则匹配所有/protected/开头的请求,再用Map指令根据路径映射到对应后端,只需要维护一处认证逻辑:
- 在Nginx的
http块中添加Map配置:
map $request_uri $protected_backend { ~^/protected/application1 http://localhost:4501; ~^/protected/application2 http://localhost:4502; ~^/protected/ http://localhost:4500; }
- 修改location配置:
location ~ ^/protected/ { auth_request /auth; auth_request_set $auth_status $upstream_status; proxy_set_header X-Real-IP $remote_addr; proxy_pass $protected_backend; } location = /auth { internal; proxy_pass http://localhost:8081/welcome; proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; }
验证与重载
修改配置后,先执行以下命令检查语法是否正确:
nginx -t
确认无错误后,重载Nginx使配置生效:
nginx -s reload
内容的提问来源于stack exchange,提问作者jansemrau
相关产品推荐
相关产品推荐

