Nginx auth only for given location

13,565

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 .

Share:
13,565

Related videos on Youtube

YardenST
Author by

YardenST

Updated on September 18, 2022

Comments

  • YardenST
    YardenST almost 2 years

    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.

  • Michael Hampton
    Michael Hampton about 11 years
    The order in which the location blocks appear is irrelevant.
  • Danack
    Danack about 11 years
    It's not for preg block - nginx.org/en/docs/http/request_processing.html "Then nginx checks locations given by regular expression in the order listed in the configuration file." I realise that doesn't apply here, but it is nice to keep them in order.