Score:0

Apply NGinx redirects only to main domain excluding subdomains

de flag

I have a setup of a PHP application listening in several hosts, for example:

maindomain.com a.maindomain.com b.maindomain.com

Some routes in maindomain.com need to be redirected. For that, I configured this redirection time ago:

rewrite ^/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;

Which makes all requests to maindomain.com/myroute/ redirect to maindomain.com/new-myroute.

The thing is that this redirects also apply to the rest of the subdomains, making a.maindomain.com/myroute redirect to maindomain.com/new-myroute.

I would like to exclude these subdomains from applying that redirection, leaving routes type a.maindomain.com/myroute untouched.

I've tried with different rewrites, like

rewrite ^https://maindomain.com/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;

rewrite ^maindomain.com/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;

rewrite maindomain.com/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;

But none of them work.

Any ideas about how to apply the redirect only to the main domain? Thanks.

Edit: the server name has a wildcard, listening to all possible subdomains that could exist:

server_name maindomain.com *.maindomain.com;
Score:1
in flag

Either use a separate server block or use an if condition

if ($host = "example.com") {
    rewrite ^/myroute/(.*)$ http://$server_name/new-myroute/$1 permanent;
}
Naroh avatar
de flag
Can't believe I didn't think of checking the $host var. Thanks!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.