Search code examples
.htaccess

.htaccess rewrite rule to redirect all pages from one domain to another EXCEPT for one specific URL?


I've looked through at least 50 different questions and posts on here on this topic, and tried everything and anything and still can't figure out how to do this.

I need to redirect all pages/URLs from domain1.com to domain2.com EXCEPT FOR a specific URL like domain1.com/paypal/ipn (to prevent Paypal IPN notifications from being broken... long story).

How do I pull that off/write that in terms of RewriteRules and RewriteConds...?

I've literally tried everything and I can easily get the domain1.com to domain2.com redirect:

    RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.com$ [NC]
    RewriteRule (.*) https://www.domain2.com%{REQUEST_URI} [R=301,L]

But that other requirement, to ignore and skip a specific URL from ever being redirected in any way, nothing works so far...

Anyone?


Solution

  • To exclude a specific page from the redirection you could use the following :

    RewriteCond %{REQUEST_URI} !/paypal/ipn [NC]
    RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.com$ [NC]
    RewriteRule (.*) https://www.domain2.com%{REQUEST_URI} [R=301,L]
    

    If there are multiple pages or URIs to exclude, you can either use RewriteCond with OR flag or use a regex based pattern in the rule

    Multiple conditions :

    RewriteCond %{REQUEST_URI} !/paypal/ipn [NC,OR]
    RewriteCond %{REQUEST_URI} !/foo/bar [NC]
    RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.com$ [NC]
    RewriteRule (.*) https://www.domain2.com%{REQUEST_URI} [R=301,L]
    

    Regex based pattern :

    RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.com$ [NC]
    RewriteRule !(page1|page2) https://www.domain2.com%{REQUEST_URI} [R=301,L]
    

    Make sure to clear your browser cache before testing this new 301 reditect.