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?

  • Are there too many subdomains to hardcode them? – jordanm Jan 25 '18 at 4:50
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.)

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.