I want if my visitors go to subdomain.example.com that they get redirected to anothersubdomain.example.com. And if they go to css.subdomain.example.com that they get redirected to css.anothersubdomain.example.com etc.
I’ve tried the following regexes (with preg_match):
Attempt 1:
if(preg_match('#(([\w\.-]+)\.subdomain|subdomain)\.example\.com#', $_SERVER['SERVER_NAME'], $match)) {
header('Location: http://'.$match[1].'anothersubdomain.example.com/');
}
If they go to: subdomain.example.com they get redirected to: anothersubdomain.example.com
But If they go to: css.subdomain.example.com they get redirected also to: subdomain.example.com – So that is not working
Attempt 2:
if(preg_match('#([\w\.-]+)\.subdomain\.example\.com#', $_SERVER['SERVER_NAME'], $match)) {
header('Location: http://'.$match[1].'.anothersubdomain.example.com/');
}
If they go to: css.subdomain.example.com they get redirected to: css.anothersubdomain.example.com
But If they go to: subdomain.example.com they get redirected to: .subdomain.example.com – And that URL is not valid so also this attempt is not working.
Somebody has an answer? I want not to use nginx or apache rewrites.
Thanks in advance.
This worked for me:
What I did is made the capturing group for the “first” subdomain optional. So, if you printed out the results like so:
You’d get as output:
Now to apply it to your needs: