Reputation: 10564
I want to redirect requests on two conditions using Nginx.
This doesn't work:
if ($host = 'domain.example' || $host = 'domain2.example'){
rewrite ^/(.*)$ http://www.domain.example/$1 permanent;
}
What is the correct way to do this?
Upvotes: 73
Views: 126629
Reputation: 2465
Another version is to map it to one string and then evaluate it via regex. In this case the if condition is: $arg_version && $request_method = "GET"
map "$arg_version:$request_method" $bypass_cache {
default 1;
~^(.+):GET$ 0;
}
location / {
if ($bypass_cache = 0) {
expires max;
}
...
}
Upvotes: 1
Reputation: 394
I think the easiest way to do it it's just use regular expression:
if ($host ~ "domain.example|domain2.example") {
rewrite ^/(.*)$ http://www.example.com/$1 permanent;
}
But it's good only when you have only strings; for complex logic, sure, it is not correct.
Upvotes: 6
Reputation: 61
Rewriting multiple domains to a single domain and avoiding a looping condition in the browser.
server {
listen 80;
server_name www.wanted_domain.example wanted_domain.example www.un_wanted_domain.example un_wanted_domain.example;
if ($host = 'un_wanted_domain.example'){
return 301 $scheme://www.wanted_domain.example$request_uri;
}
if ($host = 'www.un_wanted_domain.example'){
return 301 $scheme://www.wanted_domain.example$request_uri;
}
Upvotes: 6
Reputation: 10314
Here's a declarative approach:
server {
listen 80;
server_name `domain.example` `domain2.example`;
return 301 $scheme://www.domain.example$uri;
}
server {
listen 80 default_server;
server_name _;
#....
}
Upvotes: 7
Reputation: 91
another possibility would be
server_name domain.example domain2.example;
set $wanted_domain_name domain.example;
if ($http_host != $wanted_domain_name) {
rewrite ^(.*)$ https://$wanted_domain_name$1;
}
so it will redirect all to one specific but it's based on the use case I guess
Upvotes: 7
Reputation: 18290
The correct way would be to use a dedicated server for the redirect:
server {
server_name domain.example domain2.example;
rewrite ^ http://www.domain.example$request_uri? permanent;
}
Upvotes: 25
Reputation: 9529
I had this same problem before. Because Nginx can't do complex conditions or nested if statements, you need to evaluate over 2 different expressions.
set a variable to some binary value then enable if either condition is true in 2 different if statements:
set $my_var 0;
if ($host = 'domain.example') {
set $my_var 1;
}
if ($host = 'domain2.example') {
set $my_var 1;
}
if ($my_var = 1) {
rewrite ^/(.*)$ http://www.domain.example/$1 permanent;
}
Upvotes: 118