O
O
Omniverse2019-03-27 03:31:58
Nginx
Omniverse, 2019-03-27 03:31:58

How to add HTTP Basic auth to nginx?

How to correctly assign http basic auth to a directory and all files in it in nginx.
Contents of /etc/nginx/sites-available/default:

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

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.php index.html index.htm index.nginx-debian.html;

        server_name 111.111.111.11;

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

        location /admin {
            auth_basic "Admin Login";
            auth_basic_user_file /etc/apache2/.htpasswd;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                
                fastcgi_pass unix:/run/php/php7.3-fpm.sock;
        }

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

It is necessary to put authorization on the directory /var/www/html/admin
The problem is that authorization does not work if you access files in this directory, for example site.ru/admin/index.php
How to fix this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2019-03-27
@Omniverse

server {
        listen 80 default_server;
        listen [::]:80 default_server;
        root /var/www/html;
        index index.php index.html index.htm index.nginx-debian.html;
        server_name 111.111.111.11;
        location / {
                try_files $uri $uri/ /index.php?$query_string;
        }
        location ^~ /admin/ {
            auth_basic "Admin Login";
            auth_basic_user_file /etc/apache2/.htpasswd;
            location ~ \.php$ {
                    include snippets/fastcgi-php.conf;
                    fastcgi_pass unix:/run/php/php7.3-fpm.sock;
            }
        }
        location ~ /\.ht {
                deny all;
        }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question