Home > database >  .htaccess Redirect except for Root of a single domain
.htaccess Redirect except for Root of a single domain

Time:04-12

Assuming I have three domains: domain1.tld, domain2.tld and domain3.tld

All request should redirect to newdomain.tld/new except for the root of domain1.tld. But unfortunately my exception is not working:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain1\.tld$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domain1\.tld$
RewriteRule ^/$ https://newdomain.tld/new [L,R=301]

RewriteCond %{HTTP_HOST} !^domain1\.tld$ [OR]
RewriteCond %{HTTP_HOST} !^www\.domain1\.tld$
RewriteRule ^(.*)$ https://newdomain.tld/new [R=301,L]

CodePudding user response:

Your first rule would seem to perform the specific redirect you are trying to prevent, if it wasn't for the RewriteRule pattern ^/$, which will never match, so the first rule doesn't actually do anything.

The second rule doesn't redirect any requests to domain1.tld, so again, domain1.tld/ is not redirected by the second rule either.

Make sure you are not seeing a cached response. 301 (permanent) redirects are cached persistently by the browser, so always test with a 302 first to avoid potential caching issues.

A couple of additional assumptions:

  • newdomain.tld points to a different server.

  • You do not need to serve any static resources (CSS, JS, images, etc) from the page at domain1.tld/ - since these will be redirected to newdomain.tld. The exception is literally only for requests to the document root.

Try it like this instead:

RewriteEngine On

# Exception for "domain1.tld/"
RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.tld [NC]
RewriteRule ^$ - [L]

# Everything else redirects to "newdomain.tld/new"
RewriteRule ^ https://newdomain.tld/new [QSD,R=301,L]

Note that the RewriteRule pattern (first argument) matches against the URL-path, less the slash prefix. ie. ^$ (an empty URL-path) matches the root. (You would only use ^/$ in a server context.)

NB: You will need to clear your browser cache before testing and test with a 302 first.

  • Related