Nginx – unable to correctly configure nginx with HTTP auth on a sub-directory for uWSGI

authenticationconfigurationnginxuwsgiweb-server

I have an nginx.conf that looks something like this:

server {
    server_name subdomain.example.com;

    listen 443 ssl;
    ssl_certificate      /srv/ssl/something.crt;
    ssl_certificate_key  /srv/ssl/something.key;

    access_log /var/log/something-nginx-access.log;
    error_log /var/log/something-nginx-error.log;

    location /private { try_files $uri @yourapplication; }
    location @yourapplication {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:3131;

        auth_basic "Restricted";
        auth_basic_user_file /home/ubuntu/something.htpassword;
    }

    location / { try_files $uri @yourapplication; }
    location @yourapplication {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:3131;
    }

    keepalive_timeout 70;
}

server {
    listen 80;
    server_name subdomain.example.com;

    access_log /var/log/something-nginx-access.log;
    error_log /var/log/something-nginx-error.log;

    location /private { try_files $uri @yourapplication; }
    location @yourapplication {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:3131;

        auth_basic "Restricted";
        auth_basic_user_file /home/ubuntu/something.htpassword;
    }

    location / { try_files $uri @yourapplication; }
    location @yourapplication {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:3131;
    }
}

That is to say — I'm running my app over http and https, and forwarding all request to uWSGI, which is running a Flask application.

I wish to have a private path, /private/ where anything underneath requires HTTP AUTH. Any other paths should not require auth.

My problem is that nginx is asking for auth no matter where I make a request, e.g., '/', '/cool_page'.

How can I configure nginx correctly to only ask for authentication under /private?

Finally, the config seems to have a lot of repetition etc, is there a way of reducing my configuration down further?

Sorry, I'm new to nginx!

Best Answer

Currently you have two named locations with the same name in one server section. This will cause nginx to always take the first one defined. To solve this rename one of the named locations. Name one @private and the other @public for example.