Got a bit stuck here. I'd like a nice simple Nginx "include"able snippet that requires HTTP AUTH for the location it is include-ed in, AND forces a redirect to HTTPS if not already.
I came up with this:
# /etc/nginx/snippets/requirelogin-staff.conf
if ($https != "on") {
return 301 https://$server_name$request_uri;
}
auth_ldap "Login Required";
auth_ldap_servers staff;
and used it like this (silly example for brevity, real world we have django serving / and /static/ as a resource files shortcut):
location / {
include snippets/requirelogin-staff.conf;
try_files $uri $uri/index.html $uri.html =404;
location /static {
alias /var/www/webroot/liv/static;
}
}
It works great for anything handled by location /
wget -S shows it is first issuing a 301 redirect to the same URL but with the https protocol. Then it comes back with a 401 correctly.
Problem is for URLs under /static
The auth kicks in by directive inheritance.
But it seems the "if ($https != "on")..." is not being inherited into the nested location block.
So a wget -S goes directly to the 401, inviting the user to log in using an insecure connection, which of course is a Bad Thing.
I can sort of see why the "if" is having problems (try_files does not inherit either).
But it leaves me rather stuck.
Can any kind soul suggest perhaps a cleaner approach? The one rule is (ideally) that I'd like the AUTH to be required in one or more locations by a neat single line "include" to avoid mistakes.
And inheritance would be nice - again to avoid mistakes. Sure, we can run that "include" on every location block, and it does work. But if we guard "/" it would be nice to know that we have guarded the entire site and a developer innocently adding another location block cannot suddenly punch a security hole wide open.
Many thanks,
Tim