location rewrite for multiple domains

John picture John · Nov 1, 2012 · Viewed 8.9k times · Source

I am working on multiple projects so I have multiple domains :

1. domain1
2. domani2

how to rewrite for example

domain1/user to domain1/?page=user,

domain2/user to domain2/clientArea/userMain

Now I am using :

   location /user {
     rewrite ^/user$ /?page=user;
   }

but it rewrites all my domains.

P.S : I am new to nginx, and I am using Winginx local server;

Answer

cobaco picture cobaco · Nov 1, 2012

There's 2 ways to do this depending on whether you have 1 or 2 server-blocks (if you expect lots of configuration differences between the 2 domains use 2, if the 2 domains have mostly the same content use 1)

in the case of 2 server-blocks config looks like this:

server {
  server_name domain1;      
  location /user/ { rewrite ^ $scheme://$host/?page=user; }
  # add in rest of domain 1 config
}

server {
  server_name domain2;
  location /user/ { rewrite ^ $scheme://$host/clientArea/userMain; }
  # add in the rest of your domain 2 config

}

in the case of a single server-block it would look like this:

server {
  server_name domain1 domain2;
  location /user/ {
    if ($host = domain1) { rewrite ^ $scheme://$host/?page=user; }
    if ($host = domain2) { rewrite ^ $scheme://$host/clientArea/userMain; }
  }
}

Note: that you can use the ^ regex as rewrite condition because because the location /user/ block it's in already selects out the url's you want to rewrite. That makes it slightly more efficient as the regex will be matched faster.