Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx.conf redirect multiple conditions

Tags:

redirect

nginx

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?

like image 904
mark Avatar asked Jan 28 '11 21:01

mark


4 Answers

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;
}
like image 113
Chris Barretto Avatar answered Nov 19 '22 07:11

Chris Barretto


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;
}
like image 31
kolbyjack Avatar answered Nov 19 '22 05:11

kolbyjack


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  _;
    #....
}
like image 7
Cole Tierney Avatar answered Nov 19 '22 06:11

Cole Tierney


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

like image 6
shadowdroid Avatar answered Nov 19 '22 05:11

shadowdroid