Showing posts with label nginx htpasswd. Show all posts
Showing posts with label nginx htpasswd. Show all posts

Wednesday, April 3, 2019

nginx htpasswd for a django or proxy pass url location

When you try to configure htpasswd for a url location in nginx, you may get error connection time out, Incorrect Redirect or 404 not found. Most of the time reason is incorrectly configured proxy pass. If there is python or ruby based app where you have used proxy pass to access your web application, this error is very much common.

Tricky part if you try to set an htpasswd on login page but you do not land on My account page after login. It shows 404 not found and when you remove your htpasswd, this error does not show up after entering your login credentials.

So how can you set htpasswd successfully for a url location?

Solution :
Open nginx configuration file where you have set virtualhost for your domain. Add this location snippet in it. Add it below location / { ... }

Suppose you want to set htpasswd on login url i.e. http://domain.com/login. It should prompt htpasswd. Rest of the site should work fine without htpasswd.
  location /login {

        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host; 
        proxy_pass         http://127.0.0.1:8000$uri;
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
Use $uri in proxy_pass attribute after port. You will not get 404 Not Found error after login.