Search code examples
.htaccessmod-rewritehttp-status-code-301

redirect one domain to the other while removing a subdirectory from the uri


I am trying to redirect a third level domain (sub.domain1.com) but only if it matches a subdirectory:

http://sub.domain.com/somefolder

This will then be redirected to another domain (domain2.com) but needs to remove the /somefolder part so say this:

http://sub.domain.com/somefolder/about

Will read like this upon redirect:

http://domain.com/about

This is what I have tried so far and It seems to not be working:

RewriteEngine On
RewriteCond %{HTTP_HOST} (^|\.)sub\.domain1\.com$ [NC]
RewriteCond %{REQUEST_URI} ^/somefolder$ [NC]
RewriteRule ^/somefolder/$ https://domain2.com/$ [R=301,L]

Can someone tell me what I did wrong? I am starting to understand the htaccess but it still reads like voodoo to me...

Note: Both domains are pointing to the same server except domain1.com points to the root web folder and domain2.com points to /webroot/somefolder so it is a subdirectory inside of the root.


Solution

  • You need to add a grouping in your regex and backreference in the redirect:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} (^|\.)sub\.domain1\.com$ [NC]
    RewriteRule ^somefolder/(.*)$ https://domain2.com/$1 [R=301,L]
    

    And you don't need the condition to check the request URI, since you're already doing that in the rule's regex.