user762579
user762579

Reputation:

nginx rewrite rules from main domain to subdomain

In my nginx domain.cong , I wrote the following rewrite rules ... when a request hits the main domain ( with or without www) it shoudl redirect ot the blog subdomain , but it seems to be wrong ...

server {
....
##### Rewrite rules for domain.tld => www.domain.tld #####
if ($host ~* ^([^.]+\.[^.]+)$) {
    set $host_without_www $1;
    rewrite ^(.*) $scheme://www.$host_without_www$1 permanent;
}

##### Rewrite rules for www.domain.tld => subdomain.domain.tld #####
if ($host ~* 'www\.[^.]+\.[^.]+$')  {
    set $host_without_www $1.$2;
    rewrite ^(.*) $scheme://subdomain.$host_without_www$1 permanent;
} 
...
} 

The first rule is correct:
domain.tld => www.domain.tld
but not the second one giving only
www.domain.tld => subdomain.
should be
www.domain.tld => subdomain.domain.tld

Upvotes: 2

Views: 7800

Answers (2)

user762579
user762579

Reputation:

I guess I found the solution , modifying the 2nd rewrite rule:

##### Rewrite rules for www.domain.tld => subdomain.domain.tld #####
if ($host ~* www\.(.*)) {
  set $host_without_www $1;
   rewrite ^(.*)$ http://subdomain.$host_without_www$1 permanent;
}

it seems to be running fine until then

Upvotes: 0

SuddenHead
SuddenHead

Reputation: 1503

Your setup seems a little overcomplicated, and it's not a best practice to match for $host in "if"'s. If you have only one domain, it's simple:

server {
    # ...
    server_name domain.tld www.domain.tld;
    return 301 $scheme://subdomain.domain.tld$request_uri;
}

server {
    server_name subdomain.domain.tld;
    # ...
}

If you have many domains, setup is similar, just use regex and capture variables at server_name

Upvotes: 9

Related Questions