Search code examples
.htaccessmod-rewritehttp-redirectforward

Redirect a directory in a forwarded domain to another url with htaccess


Trying to get a directory in a forwarded domain to redirect to a new page in a url, while maintaining a rule that the rest of the site get redirected to the root of the new url.

This is the current code on the htaccess

RewriteCond %{HTTP_HOST} ^.*forwardeddomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.mainsite.com [R=301,L]

This forwards anything in the forwarded domain to the main site. But now they need to add an exemption rule to forward one directory url in that domain to another part of the main site. I tried this code, but it doesn't work:

RewriteCond %{HTTP_HOST} ^.*forwardeddomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.mainsite.com [R=301,L]
redirect 301 forwardeddomain.com/example/ http://www.mainsite.com/example.html

Haven't found anything in search for this particular issue. I don't have access to the domain registries, only ftp and htaccess.

In other words:

forwardeddomain.com and forwardeddomain.com/anything/ should forward to mainsite.com, but only forwardeddomain.com/example/ should forward to mainsite.com/example.html


Solution

  • You are mixing mod-rewrite declarations (RewriteCond and RewriteRule) with that of mod-alias (redirect). Use just one of them:

    RewriteRule ^example/$ http://www.mainsite.com/example.html [R=301,L]
    
    RewriteCond %{HTTP_HOST} ^.*forwardeddomain\.com$ [NC]
    RewriteCond %{REQUEST_URI} !^/example/ [NC]
    RewriteRule ^ http://www.mainsite.com [R=301,L]