Nginx password protect not working

nginxpassword

I'm having problems setting a password on the landing page of my website.
I've seen this question asked a few times and tried the upvoted fixes in each post. So far I've tried changing permissions of .htpasswd , changing the location of .htpasswd, using the absolute path location of .htpasswd, and placing auth_basic and auth_basic_user_file directives outside of 'location' and in the main 'server' block but the pop-up asking for username and password is still not showing up when I go to my URL. What I'd like is for a password prompt to pop up when I browse to my main URL not any specific directory or file. I've looked and followed through many tutorials and have used the htpasswd command to create the .htpasswd file. From what I understand this is the correct configuration of /etc/nginx/sites-enabled/default. What am I doing wrong here?

This is my config file:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/html;
    server_name example.com www.example.com;
    return 310 https://$server_name$request_uri;

    location / {
            try_files $uri $uri/ =404;
            auth_basic "Under Construction";
            auth_basic_user_file /etc/nginx/.htpasswd;
    }
 }

Best Answer

Your return statement overrides the location statement.

You need to have a configuration like this:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/html;
    server_name example.com www.example.com;

    location = / {
            try_files $uri $uri/ =404;
            auth_basic "Under Construction";
            auth_basic_user_file /etc/nginx/.htpasswd;
    }

    location / {
        return 310 https://$server_name$request_uri;
    }

}

So, the location = / statement matches exactly one path, here it is the root URI for the site.

Then the location / matches all the other paths on the site.

nginx parses location block so that the location with = is always used if multiple location blocks match the same path.