【问题标题】:Laravel + Nginx + Basic Auth: how to leave some routes unprotected?Laravel + Nginx + Basic Auth:如何让一些路由不受保护?
【发布时间】:2021-08-24 22:00:38
【问题描述】:

我们有 Nginx 并使用它来服务于 Laravel 8 项目

我需要通过基本身份验证来保护这个演示项目。

它可以工作,使用 nginx 和 auth_basic_file 指令

auth_basic            "My DEMO";

location ~ ^/(api|public|images)/.* {
    auth_basic off;
    try_files   $uri $uri/ /index.php?$query_string;
}



location ~ \.php$ {

    # Protect access
    auth_basic_user_file  /etc/nginx/auth/.htpasswd;

    add_header      X-Dovesono-php 1;
    fastcgi_pass    unix:/run/php/php7.4-fpm.sock;
    fastcgi_index   index.php;
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param   PATH_INFO $fastcgi_path_info;
}

我的目标

我需要让 /api/ 的整个块不受保护

问题

实际上,使用上述配置,浏览器会在每次对 /api/ 的 ajax 调用时要求我进行身份验证。 此外,即使插入正确的用户名和密码,它也会无限期地重新询问

【问题讨论】:

    标签: php laravel nginx http-authentication


    【解决方案1】:

    我用这个解决了:

    server {
       ....
       auth_basic_user_file /etc/nginx/auth/.htpasswd;
    
      location / {
        auth_basic   "My DEMO";
        try_files    $uri $uri/ /index.php?$query_string;
      }
    
      location ~ \.php$ {
        ... ...
      }
    
      location /api/ {
        auth_basic   off;
        try_files    $uri /index.php?$query_string;
      }
    
    }
    

    如果首先匹配/api/,则没有设置身份验证,然后导致重新启动解析,该解析将使用location ~ \.php$结束。

    所以页面被提供,但没有询问 http 基本身份验证

    对于所有其他路由,它会应用 auth_basic,然后重新启动解析,并以 location ~ \.php$ 结束

    因此页面已提供,但要求 http 基本身份验证

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 2022-11-16
      • 2021-11-02
      • 1970-01-01
      • 2021-11-23
      • 2020-09-11
      • 1970-01-01
      • 2021-08-06
      • 2018-08-11
      相关资源
      最近更新 更多