

新闻资讯
技术学院通过 nginx 的 `location = /path` 精确匹配和 `return 404` 指令,可限制仅允许 `/blog`、`/contact`、`/faq` 等白名单路径访问,其他路径(如 `/test`)直接返回标准 404 页面,同时保留基础认证等通用逻辑。
要实现“仅放行特定路径(如 /blog、/contact、/faq),其余所有未匹配路径统一返回 404”,关键在于优先级控制与精确匹配。Nginx 的 location 匹配遵循严格优先级规则:=(精确匹配) > ^~(前缀匹配且不继续正则) > 正则匹配 > 普通前缀匹配。因此,我们应将所有需拒绝的路径用 location = 显式声明,并置于通用 location / 之前。
以下是推荐配置方案(适用于少量白名单路径):
# 先定义所有需返回 404 的非法路径(支持任意数量,但建议 ≤50 条以保可维护性)
location = /test { return 404; }
location = /admin { return 404; }
location = /tmp { return 404; }
# ... 其他禁止路径
# 白名单路径:显式允许并交由 PHP 处理(或静态服务)
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 捕获的请求
location / {
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
# 注意:此处不再使用 try_files 跳转 index.php,
# 因为只有白名单路径才应进入应用逻辑
return 404;
}✅ 优势说明:
⚠️ 注意事项:
判断(参考 Nginx 官方 map 模块文档),避免配置臃肿; 总结:通过合理利用 location = 的高优先级特性,配合清晰的路径分类策略,即可在不依赖后端的情况下,由 Nginx 层面高效、安全地实现 URL 白名单访问控制。