3

I have a client who has a domain like this-site.com and also thissite.com Without going into the entire issue behind it, we need to redirect any incoming request to any *.this-site.com to the matching *.thissite.com.

So for example:

subdomain1.this-site.com -> subdomain1.thissite.com
subdomain2.this-site.com -> subdomain2.thissite.com
subdomain3.this-site.com -> subdomain3.thissite.com

Is there a way to preserve the first part of the URL and pass it on to the second domain?

galoget
  • 235
  • 1
  • 9

1 Answers1

1

Assuming all these subdomains resolve to the same place on the filesystem then... to redirect from this-site.com to thisstite.com whilst preserving the subdomain and remainder of the URL (ie. URL-path and query string), you can do something like the following, using mod_rewrite, near the top of your .htaccess file in the root of your site:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^([^.]+)\.this-site\.com [NC]
RewriteRule ^ https://%1.thissite.com%{REQUEST_URI} [R=302,L]

I've assumed HTTPS. This redirects https://<subdomain>.this-site.com/<url-path>[?<query-string>] to https://<subdomain>.thissite.com/<url-path>?<query-string>.

The %1 is a backreference to the first captured group in the last matched CondPattern. In other words, this matches the subdomain (([^.]+) part in the preceding regex) in the requested hostname.

Note also:

  • This will redirect all subdomains, including www.
  • But it won't redirect sub-subdomains, eg. subsubdomain.subdomain1.thissite.com will not be redirected.
  • And it will only redirect subdomains, so it won't redirect this-site.com.

This is also a temporary (302) redirect. If this is intended to be permanent then change the 302 to 301, but only after you have confirmed it is working OK. (301s are cached hard by the browser so can make testing problematic.)

MrWhite
  • 12,647
  • 4
  • 29
  • 41