...the MAYBE-dup answer does solve my problem, but the question doesn't.
Do TWO things:
Keep subdomain before
Keep path after
I can't find ONE .htaccess
or Apache config that does BOTH anywhere on SE or elsewhere on the web:
Via Apache .htaccess
rewrite, forward the old domain, but keep BOTH the same subdomain
AND path/after
.
From:
samesubdomain.
domain1.tld1
/same/path
To:
samesubdomain.
domain2.tld2
/same/path
I have many subdomains AND trailing addresses. I am migrating an old site, but need my old subs and their pages to still work on the new domain.
Not-but-close duplicates: (The answers address my problem, but the question itself does not describe my problem, but this solved my problem also.)
Redirect wildcard subdomain to same subdomain on different domain
Courtesy the MAYBE-dup answer, for the subdomain, I currently have:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+\.)?domain1.com$ [NC]
RewriteRule ^ http://%1domain2.com%{REQUEST_URI} [R=301,L]
...now, I need to add the/path
half WITHOUT conflicting with this code.
Although the linked question doesn't specifically state this, the code does actually copy the URL-path (and any query string) as well. Although the answers are admittedly lacking in any explanation.
Assumptions:
domain1.tld1
(with no subdomain) does not redirect todomain2.tld2
.Near the top of your root
.htaccess
file:The
RewriteCond
directive captures the subdomain from the request. The%1
backreference in theRewriteRule
substitution is a backreference to the captured subdomain (ie.([^.]+)
).The
$1
backreference contains the URL-path, captured by theRewriteRule
pattern, ie.(.*)
.Note that I specifically omitted the trailing
$
(end-of-string anchor) on the CondPattern in order to match FQDN, that end in a dot.Any query string is passed through unchanged.
Note that this is currently a 302 (temporary) redirect. Always test with 302s to avoid caching issues. If you've previously tested with 301s then you will need to make sure you've cleared your browser cache.
The code already contains the URL-path part. That's what the
%{REQUEST_URI}
part is in theRewriteRule
substitution string. TheREQUEST_URI
server variable contains the full URL-path. This is just another way of doing the same thing as I did above - I used a backreference$1
instead. (Note that theREQUEST_URI
server variable contains the slash prefix, whereas the backreference I used does not, hence the difference in slashes in the substitution string.)This code is missing a backslash escape on the literal dot in
.com
.Note that this solution makes the subdomain optional. It will redirect
domain1.com
(no subdomain) todomain2.com
.