I have nginx running multiple domains under a single server directive as
server {
listen 80;
server_name www.domain.com;
server_name x.domain.com;
server_name y.domain.com;
----
----
----
}
Now, I need to use location directive to match a subdomain and apply basic auth to it. The equivalent of
location x.domain.com {
auth_basic "Admin Login";
auth_basic_user_file /etc/nginx/.htpasswd;
}
How do I do this?
You can use a regular expression to capture the subdomain and then use it later in your location.
Alternatively, it might be preferable to move all common configurations to an other file, and then create server blocks per-subdomain and include the external file.
(repeat for other servers)
You don't need to use the location directive if you use map. This is the most simple solution and equivalent i can think of. You can name the htpasswd files according to your $http_host e.g.
x.domain.com.htpasswd
.One option is to return an error and send that error to a location that handles the HTTP authentication:
If you have multiple (sub)domains and they do not behave exactly alike then you use multiple server blcoks. Sorry but that's seriously the best way, even though you'll have a larger configuration.
You can do a ghetto hack by using something like if ($http_host ~ foo) but then you'll most likely run afoul of the unpredictable and weird behaviour of if as documented here: http://wiki.nginx.org/IfIsEvil
Don't try to outsmart Nginx, just use the options it gives you and you'll have far less headaches.