Search code examples
phpsymfonynginxbasic-authentication

Nginx + Symfony. Basic auth except for a subfolder


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.


Solution

  • 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;
    }