You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 22.04下Nginx目录密码保护失效,PHP脚本可无验证访问求助

Nginx auth_basic 对PHP脚本失效的排查方向
  • PHP请求优先级高于auth验证规则
    Nginx中正则表达式类型的location ~ \.php$优先级高于前缀匹配的location /servis,导致PHP请求直接走FastCGI处理,跳过了auth_basic验证。
    解决:使用location ^~ /servis(^~强制前缀匹配优先于正则)包裹目录规则,或者把auth_basic配置直接加到PHP处理的location块中。示例配置:

    location ^~ /servis {
        auth_basic "Restricted Area";
        auth_basic_user_file /etc/nginx/conf.d/.htpasswd;
    
        location ~ \.php$ {
            fastcgi_pass unix:/run/php/php8.2-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
    
  • 密码文件权限不足
    Nginx运行用户(通常为www-data或nginx)没有读取/etc/nginx/conf.d/.htpasswd的权限,导致验证逻辑失效。执行以下命令修复:

    sudo chown nginx:nginx /etc/nginx/conf.d/.htpasswd
    sudo chmod 600 /etc/nginx/conf.d/.htpasswd
    

    注意替换nginx为你的Nginx实际运行用户。

  • 配置语法错误或位置错误
    先执行sudo nginx -t检查配置文件是否有语法错误。同时确认auth_basic配置是否放在了能覆盖所有子请求的位置,比如不要仅在静态资源的location中配置,要确保PHP请求的路径也能命中验证规则。

  • 未正确重载Nginx配置
    重启服务器不等于重载Nginx配置,建议先验证配置语法,再执行重载命令:

    sudo nginx -t
    sudo systemctl reload nginx
    
  • 浏览器缓存了验证凭据
    若之前成功通过验证,浏览器可能缓存了会话凭据,导致测试时未弹出验证框。使用隐私模式打开页面,或清除浏览器缓存后重试。

内容的提问来源于stack exchange,提问作者user3523426

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 08:23:22