The recommended way would probably be using a map
, also because these variables are evaluated only when they are used.
Also the use of return 301 ...
is preferred over rewrites, because no regular expression have to be compiled.
Here an example of where host and user-agent as a concatenated string are compared to a single regex:
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;
}
}
And this could be even more flexible, for example if a there not 2 but more domains involved.
Here we map www.domain.com
with user-agents starting with Agent
to http://www.domain2.com
and www.domain2.com
with the exact user-agent Other Agent
to 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;
}
}
NB you will need nginx 0.9.0 or higher for the concatenated string in map to work.