Matching server host name in location directive

Can someone help me answer this question at

serverfault.comhttp://serverfault.com/questions/286828/nginx-matching-server-host-name-in-location-directive?


Posted again

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 using DRY?

On Tue, Jul 5, 2011 at 12:49 PM, Quintin P. [email protected]
wrote:

      server_name  x.domain.com;
      auth_basic "Admin Login";
     auth_basic_user_file /etc/nginx/.htpasswd;

}

How do I do this using DRY?

server {
server_name www.domain.com;
server_name y.domain.com;
include myapps.conf;
}

server {
server_name x.domain.com;
include myapps.conf;
auth_basic “Admin Login”;
auth_basic_user_file /etc/nginx/.htpasswd;
}

On Tue, Jul 05, 2011 at 11:19:23AM +0530, Quintin P. wrote:

Hi there,

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;

Now, I need to use location directive to match a subdomain and apply basic
auth to it. The equivalent of

location doesn’t match subdomains. server_name matches subdomains. Use
different server{}s for different things.

location x.domain.com {
auth_basic “Admin Login”;
auth_basic_user_file /etc/nginx/.htpasswd;
}

How do I do this using DRY?

make.

Or m4. Or a config file generator of your choice.

nginx doesn’t care how your .conf file came about, it just cares about
what is in the .conf file when it is loaded.

Don’t worry about duplication or repetition in the generated output
file. If you want to worry about repetition, do it in your input format.

Good luck,

f

Francis D. [email protected]

Thanks. This seems a bit crude, especially when you have a long server
tag. A change/bug in one server tag will now have to to replicated to
the x sub domains/server_names.
I was looking for an elegant solution without a lot of conf files.

-Quintin.

I prefer to use individual config for each site,

nginx.conf


include /etc/nginx/sites-enabled/*;

/etc/nginx/sites-enable/somesite.conf

server {
listen 80;
server_name x.domain.com;

location x.domain.com {
auth_basic “Admin Login”;
auth_basic_user_file /etc/nginx/.htpasswd;
}

}

Just my 2 cent :slight_smile: It’s helpful for me