Search code examples
nginxbasic-authenticationshopware6

BasicAuth with nginx except for a specific location (Admin/API)


I want to set up BasicAuth on a DEV installation of Shopware to prevent Google/visitors from coming to the site. I would like to keep the admin area without BasicAuth, as the SPA backend keeps asking for login on many ajax requests. In short, BasicAuth for all requests except "/admin" and "/api".

I have tried this with the following configuration. But I get the password prompt even for requests on "/admin".

Why does "auth_basic" from one location affect the other?

server {
listen [--IP--]:80;
listen [--IP--]:443 ssl http2;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_certificate /var/www/clients/client1/web7/ssl/[--DOMAIN--].crt;
ssl_certificate_key /var/www/clients/client1/web7/ssl/[--DOMAIN--].key;

server_name [--DOMAIN--] ;
root /var/www/[--DOMAIN--]/web;

.
.
.

add_header X-Robots-Tag "noindex, nofollow" always;

location @rewriteapp {
    root /var/www/[--DOMAIN--]/web/public/;
    client_max_body_size 100M;
    rewrite ^/(.*)$ /index.php last;
}

location /admin {
    alias /var/www/[--DOMAIN--]/web/public/;
    client_max_body_size 100M;
    index index.php;
    http2_push_preload on;

    rewrite ^/(.+)\.php/(.*)$ /$1.php last;

    try_files $uri @rewriteapp;

    location ~ \.php$ {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        fastcgi_index index.php;
        .
        .
        .
        http2_push_preload on;
    }
}

location / {
    alias /var/www/[--DOMAIN--]/web/public/;
    client_max_body_size 100M;
    index index.php;
    http2_push_preload on;

    rewrite ^/(.+)\.php/(.*)$ /$1.php last;

    try_files $uri @rewriteapp;

    .
    .
    .

    auth_basic "DEV";
    auth_basic_user_file /var/www/clients/client1/web6/web/public/.htpasswd;

    location ~ \.php$ {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        fastcgi_index index.php;
        .
        .
        .
        http2_push_preload on;
    }
}

}

I also tried with auth_basic off in the "/admin" location.

auth_basic off;
allow all;

Solution

  • Try this:

    server {
        location ~ .php$ {
            set $auth "Restricted";
            if ($request_uri ~ /api/.*){
                set $auth "off";
            } 
            if ($request_uri ~ /admin.*){
                set $auth "off";
            }
            auth_basic $auth;
            auth_basic_user_file /www/htdocs/shopware/.htpasswd;
        }
    }