Nginx – Redirect Based on User Agent

nginx

Here is my current 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
  }
}

it works fine, both www.domain.com and www.domain2.com serve the same content.

now I'd like to add

if the user is visiting www.domain.com and the user agent is xxx then redirect to www.domain2.com

I've searched and tried a lot of method but none of them works.

Best Answer

There are Two ways to fix this issue.

  1. Have two seperate "server" blocks for www.domain.com & www.domain2.com and add the following lines of rules to "server" block www.domain.com. This is recommended way to solve this issue.

    if ($http_user_agent ~* "^xxx$") {
       rewrite ^/(.*)$ http://www.domain2.com/$1 permanent;
    }
    
  2. If you want to manage the redirect with a single "server" block for both domains, Try below rules

    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;
    }