这是我目前的nginx conf:
server { listen 90; server_name www.domain.com www.domain2.com; root /root/app; location / { try_files $uri =404; } location ~ /([-\w]+)/(\w+)/ { proxy_pass bla bla } }
它工作正常, www.domain.com和www.domain2.com服务相同的内容。
现在我想补充一点
如果用户访问www.domain.com,用户代理是xxx,则redirect到www.domain2.com
我search了很多方法,但都没有成功。
有两种方法可以解决这个问题。
为www.domain.com&www.domain2.com提供两个单独的“服务器”块,并将以下规则添加到“服务器”块www.domain.com。 这是解决这个问题的推荐方法。
if ($http_user_agent ~* "^xxx$") { rewrite ^/(.*)$ http://www.domain2.com/$1 permanent; }
如果要为两个域使用单个“服务器”块pipe理redirect,请尝试以下规则
set $check 0; if ($http_user_agent ~* "^xxx$") { set $check 1; } if ($host ~* ^www.domain.com$) { set $check "${check}1"; } if ($check = 11) { rewrite ^/(.*)$ http://www.domain2.com/$1 permanent; }
第1步:有两个服务器块,分别为domain.com和domain2.com。
步骤2:如果使用不当,则使用正确,否则使用不当。
这是完整的解决scheme…
server { listen 90; server_name www.domain.com; root /root/app; # redirect if 'xxx' is found on the user-agent string if ( $http_user_agent ~ 'xxx' ) { return 301 http://www.domain2.com$request_uri; } location / { try_files $uri =404; } location ~ /([-\w]+)/(\w+)/ { proxy_pass bla bla } } server { listen 90; server_name www.domain2.com; root /root/app; location / { try_files $uri =404; } location ~ /([-\w]+)/(\w+)/ { proxy_pass bla bla } }
推荐的方法可能是使用map ,也是因为这些variables只有在使用时才被评估。
另外,使用return 301 ...优先于重写,因为不需要编译正则expression式。
在这里,将主机和用户代理作为连接string的示例与单个正则expression式进行比较:
map "$host:$http_user_agent" $my_domain_map_host { default 0; "~*^www.domain.com:Agent.*$" 1; } server { if ($my_domain_map_host) { return 302 http://www.domain2.com$request_uri; } }
这可能会更加灵活,例如,如果有一个不是2个,但涉及更多的域。
在这里,我们将www.domain.com与以Agent程序开始的用户代理Agent映射到http://www.domain2.com和www.domain2.com ,并使用确切的用户代理程序“ Other Agent到http://www.domain3.com :
map "$host:$http_user_agent" $my_domain_map_host { default 0; "~*^www.domain.com:Agent.*$" http://www.domain2.com; "~*^www.domain2.com:Other Agent$" http://www.domain3.com; } server { if ($my_domain_map_host) { return 302 $my_domain_map_host$request_uri; } }
注意你将需要nginx 0.9.0或更高版本的连接string在地图上工作。