Nginx仅放行单路径时,含/#的URL可通过的问题排查
Nginx特定路径访问限制问题解析
配置情况
主配置文件nginx.conf内容:
http { include mime.types; default_type application/octet-stream; upstream promo { server localhost:82; } server { listen 82; location / { add_header Content-Type text/plain; return 200 "gangam style"; } } # nginx运行在Windows机器上 include .\conf\promo.conf; } events {}
子配置文件.\conf\promo.conf内容:
server { listen 81; if ($request_uri !~ ^/$|^/gateway) { return 403; } location / { proxy_pass http://promo; } }
测试结果
- 请求
http://localhost:81/gateway或http://localhost:81/gateway/abc时返回200(符合预期) - 请求
http://localhost:81/hello时返回403(符合预期) - 请求
http://localhost:81/#/hello时返回200(不符合预期)
问题原因
URL中的#及其后续内容属于锚点(Fragment),这部分内容仅由浏览器本地解析处理,不会被发送到服务器端。当你请求http://localhost:81/#/hello时,Nginx实际接收到的请求路径是/,而你的规则^/$|^/gateway允许根路径/的访问,因此会返回200。
解决方案
根据实际需求调整配置:
- 如果不需要允许根路径
/的访问,直接移除规则中的^/$,修改为:
这样根路径if ($request_uri !~ ^/gateway) { return 403; }/会返回403,包含锚点的请求因为实际路径是/,也会被拦截。 - 如果是SPA前端路由场景,需要限制前端路由路径,这种情况无法通过Nginx直接处理(服务器收不到锚点内容),需要在前端代码中添加路由拦截逻辑,对未授权路由进行跳转或提示。
内容的提问来源于stack exchange,提问作者ivanko_p
相关产品推荐
相关产品推荐

