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

Laravel Forge部署站点如何为单一URI取消Basic Auth验证

错误原因说明

  1. 第一次配置失效核心问题:你将auth_basic全局配置和免验证location规则放在了server块外部(属于http块级别配置),不会对当前站点的请求生效。就算将规则移入server块,Laravel的动态请求会被try_files重写为指向index.php的请求,最终匹配到处理PHP的location块,该块会继承server级别的auth校验规则,你单独写的路径规则覆盖不到重写后的请求。
  2. 第二次配置循环弹框核心问题:你把auth校验规则仅放在了根location /内,站点的静态资源(js、css、图片等)会匹配到其他独立的静态资源location规则,不会走根location的校验逻辑,导致权限校验逻辑混乱出现循环验证的问题。

正确配置方案

适配Laravel + Forge的部署场景,按以下步骤操作即可:

  1. 先在Forge后台对应站点的「安全」Tab中关闭原本的全局Basic Auth,避免自动生成的全局配置冲突。
  2. 进入站点的Nginx配置编辑页,修改核心配置如下(原有其他配置保持不变即可):
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name staging.mysite.com;
    root /home/forge/staging.mysite.com/public;

    # 全局默认开启Basic Auth
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/forge-conf/staging.mysite.com/server/.htpasswd-21495;

    # 免验证URI规则,精确匹配加=,前缀匹配去掉=即可
    location = /my-unrestricted-uri {
        auth_basic off;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        # 适配重写到index.php的动态请求,匹配免验证路径时关闭校验
        set $auth_status "Restricted Area";
        if ($request_uri ~* ^/my-unrestricted-uri) {
            set $auth_status off;
        }
        auth_basic $auth_status;
        auth_basic_user_file /etc/nginx/forge-conf/staging.mysite.com/server/.htpasswd-21495;

        # 以下保持你原有PHP处理配置不变即可
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # 其他原有配置保持不变
}
  1. 配置修改完成后,先执行nginx -t校验语法是否正确,确认无报错后执行service nginx reload重载Nginx配置即可生效。
  2. 测试时建议使用浏览器无痕模式,避免之前的401缓存影响验证结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:36:03