Search code examples
.htaccesshttp-redirectmod-rewriteurl-rewritingfriendly-url

RewriteRule for subdomain to subfolder .htaccess


I'm trying to accomplish the following:

  1. non-http force to https - works
  2. www force to non-www - works
  3. website loaded from subfolder (/web) - works
  4. test.example.com load different subfolder (/test) - does not work

4, Does not work, the condition is met to go to /web. Can't understand how to change this into /test

the .htaccess code I use:

RewriteEngine On
RewriteCond %{HTTPS} !=on

RewriteCond %{HTTP_HOST} ^test.example.com$
RewriteRule ^(.*)$ /test/$1 [L,NC,QSA]

RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^example.com$ [NC,OR]
RewriteRule ^(.*)$ /example/web/$1 [L,NC,QSA]

Solution

  • With your shown samples please try following htaccess rules file here. Please make sure to clear your browser cache before testing your URLs. In case you have further more rules(apart from shown ones) then make sure these Rules are before those rules.

    RewriteEngine On
    ##Apply https to uris here..
    RewriteCond %{HTTPS} !on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
    
    ##Apply non-www to uris here..
    RewriteCond %{HTTP_HOST} ^(?:www\.)(example\.com)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R=301]
    
    ##Apply test to all uris here..
    RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
    RewriteCond %{REQUEST_URI} !^/test [NC]
    RewriteRule ^(.*)/?$ example/web/$1 [L,NC,QSA]
    
    ##Apply test to all uris here..
    RewriteCond %{HTTP_HOST} ^test\.example\.com$ [NC]
    RewriteCond %{REQUEST_URI} !^/test [NC]
    RewriteRule ^(.*)/?$ www.example.com/test/$1 [L,NC,QSA]