通过nginx location限制特定URL不可访问【编辑中】
2025-04-29 15:05 WilliamZheng 阅读(347) 评论(0) 收藏 举报需求
甲方要求漏洞修复,有如下两个链接存在未授权访问,比如要求下面两个链接存在未授权访问
192.168.10.10/proxy-jsdata-bigscreen-update/swagger-ui.html
192.168.10.10/proxy-jsdata-bigscreen-update/v2/api-docs
解决思路
根据需求,能想到有如下五种方法解决:
- 添加认证
- 使用if
- 多个location嵌套
- 使用正则表达式
- location精准匹配
方法一:添加认证
添加认证,需要使用htpasswd,有时还需要装httpd-tools包来支持,且操作较繁琐。
方法二:使用if
官方不推荐,谨记《If Is Evil》,简单来说就是if不可靠。
方法三:location嵌套
3多个location嵌套,也可以采取这种方式,但配置的时候需要小心。
方法四:使用正则表达式
# 屏蔽 /gistackinsight-service/swagger 及其所有子路径
location ~ ^/gistackinsight-service/swagger(/|$) {
deny all;
return 403; # 返回 403 Forbidden
}
# 其他正常路由配置(例如反向代理)
location /gistackinsight-service/ {
proxy_pass http://backend_server; # 替换为实际后端地址
# 其他代理配置...
}
方法五:location精准匹配(推荐)
location精准匹配,配置简单,本次采取。
需要注意仅屏蔽这两个存在未授权访问的链接,不能影响192.168.10.10/proxy-jsdata-bigscreen-update/* 后面其他任何字符串的访问。
添加两个精确匹配的 location 块,使用 = 运算符进行精确匹配,优先级高于普通前缀匹配和正则匹配。这两个location块会优先拦截对目标路径的请求,并返回403 Forbidden错误。
# 精确匹配并阻止特定路径
location = /proxy-jsdata-bigscreen-update/swagger-ui.html {
return 403; # 或者使用 deny all; 拒绝访问
}
location = /proxy-jsdata-bigscreen-update/v2/api-docs {
return 403; # 或者使用 deny all; 拒绝访问
}
# 通用转发逻辑
location /proxy-jsdata-bigscreen-update/ {
proxy_pass http://localhost:8000/;
}
测试
- 测试被阻止的路径 :
- 访问 192.168.10.10/proxy-jsdata-bigscreen-update/swagger-ui.html 应返回 403 Forbidden。
- 访问 192.168.10.10/proxy-jsdata-bigscreen-update/v2/api-docs 同样应返回 403 Forbidden。
- 测试未阻止的路径 :
- 访问 192.168.10.10/proxy-jsdata-bigscreen-update/other-path 应正常转发到 http://localhost:8000/。
WilliamZheng©版权所有 转载请注明出处! 觉得对您有帮助请点个赞哟~ 运维架构师群:833329925
浙公网安备 33010602011771号