Nginx:匹配位置指令中的服务器主机名

我有nginx在单个服务器指令下运行多个域

server { listen 80; server_name www.domain.com; server_name x.domain.com; server_name y.domain.com; ---- ---- ---- } 

现在,我需要使用位置指令来匹配一个子域名,并对其应用基本身份validation。 相当于

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

我如何做到这一点?

您可以使用正则expression式来捕获子域,然后在您的位置使用它。

 server { server_name ~^(?<sub>\.)?(?<domain>.+)$; location / { root /sites/$sub; } } 

或者,最好将所有常用configuration移动到其他文件,然后创build每个子域的服务器块并包含外部文件。

 server { server_name www.domain.com; include /etc/nginx/sites-enabled/default.inc; location / { ... } } 

(重复其他服务器)

如果你有多个(子)域,他们不完全相同,那么你使用多个服务器域。 对不起,但这是最好的方式,尽pipe你会有一个更大的configuration。

你可以通过使用if($ http_host〜foo)来做一个贫民区的黑客攻击,但如果logging在这里,你很可能会遇到不可预知和怪异的行为: http ://wiki.nginx.org/IfIsEvil

不要试图取代Nginx,只要使用它给你的选项,你就会less得多的头痛。

一种select是返回一个错误,并将该错误发送到处理HTTP身份validation的位置:

 if ($host = x.domain.com) { return 550; } error_page 550 = @xauth; location @xauth { auth_basic "Admin Login"; auth_basic_user_file /etc/nginx/.htpasswd; } 

如果您使用地图,则不需要使用位置指令。 这是我能想到的最简单的解决scheme。 您可以根据您的$ http_host命名htpasswd文件,例如x.domain.com.htpasswd

 map $http_host $auth_type { default "off"; #This will turn off auth-basic x.domain.com "Restricted"; #This or any other string will turn it back on } server { auth_basic $auth_type; auth_basic_user_file /etc/nginx/conf.d/$http_host.htpasswd; }