Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.htaccess Redirect except for Root of a single domain

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading