
本文介绍如何配置 nginx,使其仅对预定义的白名单路径(如 `/blog`、`/contact`、`/faq`)正常响应,而对其他未匹配路径(如 `/test`)直接返回标准 404 错误页,同时保留基础认证保护。
要实现“仅放行特定路径、其余一律 404”,核心思路是优先匹配显式声明的合法路径,再通过兜底规则拦截非法请求。由于你当前使用 location / { ... try_files ... } 的宽泛匹配方式,所有路径都会被重写到 /index.php,因此必须打破默认继承逻辑,改用更精确的匹配策略。
✅ 推荐方案:显式声明白名单 + 精确匹配 404 规则
假设你只允许 /blog、/contact、/faq 三个路径(及其子路径,如 /blog/post1),其余全部 404。可按如下方式重构 location 块:
# 全局启用基础认证(推荐上移至此,避免重复)
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
# 显式允许的路径 —— 使用前缀匹配支持子路径
location /blog {
try_files $uri $uri/ /index.php;
}
location /contact {
try_files $uri $uri/ /index.php;
}
location /faq {
try_files $uri $uri/ /index.php;
}
# 精确匹配非法路径(可选:针对已知无效路径快速拦截)
location = /test { return 404; }
location = /admin { return 404; }
# 【关键】兜底规则:匹配所有未被上述 location 捕获的请求
location / {
return 404;
}⚠️ 注意顺序:Nginx 按 location 块出现顺序自上而下匹配,且优先级遵循 = > ^~ > ~* > / 规则。因此必须将具体路径(如 /blog)放在通用 / 之前,否则会被兜底规则提前截断。
? 替代方案:使用 map(适用于超长白名单,如数百条)
若白名单路径极多(例如 2000+),硬编码 location 块会显著降低可维护性。此时推荐使用 map 指令在 http 块中预定义路径映射:
http {
# 在 http 块顶层定义白名单映射
map $uri $is_allowed_path {
default 0;
~^/(blog|contact|faq)(/|$) 1; # 支持 /blog 和 /blog/xxx
}
server {
location / {
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
if ($is_allowed_path = 0) {
return 404;
}
try_files $uri $uri/ /index.php;
}
}
}❗ 注意:if 在 location 中虽可用,但应仅用于简单判断(如变量比较)。此处安全,因仅做布尔判断且无副作用。
✅ 最佳实践与注意事项
- 认证位置优化:将 auth_basic 移至 server 或 http 块,避免在每个 location 中重复声明,提升可读性与性能。
- 静态资源兼容性:确保 /blog/css/style.css 等真实静态文件能被 try_files 正确命中;若存在大量静态资源,建议单独配置 location ~ \.(css|js|png|jpg)$ 提升效率。
- 404 页面定制:可通过 error_page 404 /404.html; 指向自定义错误页,并确保该路径本身在白名单中或通过 location = /404.html 显式放行。
- 测试验证:修改后务必执行 sudo nginx -t 检查语法,并用 curl -I http://yoursite/test 验证返回 404 Not Found。
综上,对于少量路径,显式 location 是最清晰、高效、易调试的方式;对于海量路径,map + if 提供了良好的扩展性。二者均能严格满足“非白名单即 404”的安全需求。










