Home > Mobile >  .htaccess 301 redirect whole URL including Domain
.htaccess 301 redirect whole URL including Domain

Time:05-31

I need to redirect around 300 URLs on a multidomain site that has the same URL structure on the different domains. For example:

https://www.example.com/de/products.html needs to be redirected to https://www.example.org/de/products.html

So my usual approach does not work:

RedirectMatch 301 /de/products.html$ /de/products.html

I would need something like

RedirectMatch 301 https://www.example.com/de/products.html$ https://www.example.org/de/products.html

which obviously doesn't work or I just didn't get to work.

Not sure if important, but it's a TYPO3 instance.

CodePudding user response:

The mod_alias RedirectMatch directive matches against the URL-path only. To match the hostname you'll need to use mod_rewrite with an additional condition (RewriteCond directive) that checks against the HTTP_HOST server variable (the value of the Host HTTP request header).

Also, since the URL structure is the same on both domains then you only need a single rule - just use the same URL-path from the initial request. No need to do one-by-one redirects as you seem to be trying to do.

For example, the following would need to go at the top of the .htaccess file before any existing rewrites:

RewriteEngine On

# Redirect everything from example.com to example.org and preserve the URL-path
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC]
RewriteRule ^ https://www.example.org%{REQUEST_URI} [R=301,L]

This checks for both example.com and www.example.com.

The REQUEST_URI server variable already contains a slash prefix, hence it is omitted in the substitution string.

Test first with a 302 (temporary) redirect to avoid potential caching issues.


UPDATE:

But I don't want to redirect all URLs, just some.

To redirect a specific URL to the same URL at the target domain, as per your original example:

# Redirect "/de/product.html" only
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC]
RewriteRule ^de/products\.html$ https://www.example.org/$0 [R=301,L]

The above redirects https://www.example.com/de/products.html only to https://www.example.org/de/products.html.

The $0 backreference contains the entire URL-path that the RewriteRule pattern matches against.

How to extend your snippet with /de/ or /fr/ etc.? For example I want to redirect example.com/de/products.html but not example.com/products.html

Maybe the above example is what you require. Alternatively, to redirect /de/<something> (or /fr/<something>) only and not just /<something>, you could do something like this:

# Redirect "/<lang>/<something>" only, where <lang> is "de" or "fr"
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC]
RewriteRule ^(de|fr)/[^/] $ https://www.example.org/$0 [R=301,L]

The above will redirect https://example.com/de/<something> to https://www.example.org/de/<something>.

  • Related