Search code examples
nginxnext.jsbasic-authenticationnginx-locationnginx-config

Nginx returns 404 after loggin in with basic authentication


I've created a website with next.js and after deployment in my own test server , everything worked as expected.As there is and admin Area, i made a configuration to protect the /admin url using nginx basic auth.Here are my steps:

  1. First i've installed the apache2-utils using sudo apt-get install apache2-utils on Ubuntu 18.04
  2. I've created my credentials by running: htpasswd /etc/nginx/.htpasswd myusername .After click on enter, i've provided a password
  3. I tried view the file content and everythinh was good because i've seen usename:hashedpassword
  4. I made the following configuration in nginx

    location /admin { auth_basic "Zone protege"; auth_basic_user_file /etc/nginx/.htpasswd; }

Here is my full configuration for that app.But i've hidden other configuration details(TLS,http redirect,etc..) :

 server {
    server_name mydomainename.com;
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
     }


    location /admin {
        auth_basic "Zone protege";
        auth_basic_user_file /etc/nginx/.htpasswd;
        try_files $uri $uri/ =404;
      } 
}

When i try to access the protected page,i get this : Login Popup

When i tap bad credentials i don't get the request page as expected.

So when i tap the expected credentials i get a 404: 404 Error

I've already read the follwing solutions: NGINX auth_basic is giving me a '404 not found' message ... NGINX htpasswd 404 not found

A tried other solutions as well even thaugh they aren't marked as solving the problem.


Solution

  • Try this ?

    server {
        server_name mydomainename.com;
        auth_basic "Zone protege";
        auth_basic_user_file /etc/nginx/.htpasswd;
    
        location / {
            auth_basic off;
    
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    
        location /admin {
            #auth_basic on;
    
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        } 
    }