Nginx auth only for given location

authenticationhttp-authenticationhttp-basic-authenticationnginx

I'm using Nginx as a reverse proxy for a python WSGI web-app.

It looks something like that:

location / {
    #auth_basic     "Administrator Login";
    #auth_basic_user_file  /var/www/static/.htpasswd;
    proxy_pass          http://mywebapp_gunicorn;
    proxy_redirect      off;
    proxy_set_header    Host            $host;
    proxy_set_header    X-Real-IP       $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
}

Inside the web application I've got some administators pages I would like to be very protected, so now I'm using some authentication inside the web application to protect them, I would like to add Nginx auth as well.

How to activate:

    auth_basic      "Administrator Login";
    auth_basic_user_file  /var/www/static/.htpasswd;

For path: /managers, but not for all other URLs.

Best Answer

You just need to add another location block before the one you currently have, to match the url you want protected.

location /managers {
    auth_basic      "Administrator Login";
    auth_basic_user_file  /var/www/static/.htpasswd;
    proxy_pass          http://mywebapp_gunicorn;
    proxy_redirect      off;
    proxy_set_header    Host            $host;
    proxy_set_header    X-Real-IP       $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
}

location / {
    proxy_pass          http://mywebapp_gunicorn;
    proxy_redirect      off;
    proxy_set_header    Host            $host;
    proxy_set_header    X-Real-IP       $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
}

Because it's before the / one, it will be used preferentially for the path /managers .