信息发布→ 登录 注册 退出

Nginx 配置:仅允许指定路径访问,其余路径返回 404

发布时间:2026-01-08

点击量:

通过 nginx 的 location 精确匹配和 try_files 指令组合,可实现仅放行 `/blog`、`/contact`、`/faq` 等白名单路径,其他所有未匹配路径(如 `/test`)直接返回标准 404 响应,同时保留基础认证保护。

要实现“仅允许特定 URL 路径(如 /blog、/contact、/faq)被访问,其余路径一律返回 404”,关键在于优先匹配显式声明的合法路径,再兜底拒绝非法路径,而非依赖 try_files 的默认 fallback 行为。

✅ 推荐方案:使用精确匹配 location + 兜底拒绝

将原有宽泛的 location / 拆解为多个精确匹配(location = /path)和一个受限的通用块,并确保认证与逻辑层级一致:

# 全局启用基础认证(推荐上移至此,避免重复配置)
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;

# 显式放行白名单路径(支持 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 = / {
    try_files $uri $uri/ /index.php;
}

# 所有其他路径均返回 404(注意:必须放在最后,且不带 auth_basic —— 它已由全局继承)
location / {
    return 404;
}
⚠️ 注意事项:location = /path 是精确匹配,优先级高于 location /,因此 /blog 不会落入兜底块;认证指令 auth_basic 放在 server 块顶层,可被所有子 location 继承,语义清晰且避免遗漏;location / 作为兜底时不可再写 try_files ... /index.php,否则非法路径仍会被 index.php 拦截,违背 404 设计目标;若需对某些路径(如静态资源 /images/)例外放行,可在兜底前添加对应 location ^~ /images/ 块。

? 替代方案:使用 map(适用于大量路径)

当白名单路径达数百或上千条时,逐条写 location = 维护成本高,此时推荐用 map 构建布尔标志:

map $uri $is_allowed {
    default         0;
    ~^/(blog|contact|faq)/?$  1;
    = /              1;
}

server {
    # ... 其他配置
    location / {
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;

        if ($is_allowed = 0) {
            return 404;
        }
        try_files $uri $uri/ /index.php;
    }
}

? 提示:map 方案更灵活,但 if 在 location 中有性能与行为限制(仅限简单判断),务必确保 $is_allowed 逻辑完备,且不与其他 rewrite 规则冲突。

✅ 最终验证方式

重启 Nginx 后测试:

curl -I http://your-site/blog     # → 200 OK
curl -I http://your-site/test     # → 404 Not Found
curl -I http://your-site/         # → 200 OK(若已配置 root path)

通过结构化 location 匹配与合理作用域设计,你既能精准控制路由权限,又能保持配置简洁可维护——这才是生产环境推荐的 Nginx 安全路由实践。

标签:# 放在  # 仅限  # 而非  # 又能  # 数百  # 可选  # 布尔  # 可在  # 适用于  # 多个  # php  # location  # map  # 继承  # if  # asic  # 作用域  # 路由  # curl  # nginx  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!