doutan3371 2016-12-14 14:37
浏览 44
已采纳

Nginx + Symfony。 除了子文件夹之外的基本身份验证

I have a symfony app under nginx server. I want to enable basic http auth but exclude everything inside the /api/ url request.

This is my current configuration for nginx:

server {
    listen 80;
    listen [::]:80;

    root /home/mysite/www/web;

    index app.php index.php index.html;

    server_name mysite.com;

    error_log  /home/mysite/logs/error.log  warn;
    access_log /home/mysite/logs/access.log;


    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /app.php$is_args$args;
    }

    # PROD
    location ~ ^/app\.php(/|$) {
        include /etc/nginx/php-mysite.conf;

        # Protect access
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

    location ~ ^/app\.php/api/(.*) {
        include /etc/nginx/php-mysite.conf;
        auth_basic "off";
    }

    location ~ /\.ht {
       deny all;
    }
}

In /etc/nginx/php-mysite.conf is the php-fpm configuration. It works well.

The problem is that it seems that every request is being handled by the the ^app.php(/|$) location directive. I am unable to configure it to disable the auth request when accessing /api/... urls.

I've spend several hours without success.

  • 写回答

1条回答 默认 最新

  • duankeye2342 2016-12-14 15:24
    关注

    Well, I don't like this solution, but it works. What I've done is to check the request_uri in the location directive, and if it starts with /api then I enable the auth basic. I would like to use two separate locations for this purpose instead of an if inside the location.

    This is the location directive, by default it is enabled and if the request matches ^/api/.*$ then the auth is set to off:

    # PROD
    location ~ ^/app\.php(/|$) {
        include /etc/nginx/php-mysite.conf;
    
        # Protect access
        set $auth "Restricted";
        if ($request_uri ~ ^/api/.*$){
            set $auth "off";
        }
    
        auth_basic $auth;
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容