.htaccess rewrite subdomain to directory .htaccess rewrite subdomain to directory apache apache

.htaccess rewrite subdomain to directory


Try putting this in your .htaccess file:

RewriteEngine onRewriteCond %{HTTP_HOST} ^sub.domain.comRewriteRule ^(.*)$ /subdomains/sub/$1 [L,NC,QSA]

For a more general rule (that works with any subdomain, not just sub) replace the last two lines with this:

RewriteEngine onRewriteCond %{HTTP_HOST} ^(.*)\.domain\.comRewriteRule ^(.*)$ subdomains/%1/$1 [L,NC,QSA]


I'm not a mod_rewrite expert and often struggle with it, but I have done this on one of my sites. It might need other flags, etc., depending on your circumstances. I'm using this:

RewriteEngine onRewriteCond %{HTTP_HOST} ^subdomain\.example\.com$RewriteCond %{REQUEST_URI} !^/subdomains/subdomainRewriteRule ^(.*)$ /subdomains/subdomain/$1 [L]

Any other rewrite rules for the rest of the site must go afterwards to prevent them from interfering with your subdomain rewrites.


You can use the following rule in .htaccess to rewrite a subdomain to a subfolder:

RewriteEngine On # If the host is "sub.domain.com" RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC] # Then rewrite any request to /folder RewriteRule ^((?!folder).*)$ /folder/$1 [NC,L]

Line-by-line explanation:

  RewriteEngine on

The line above tells the server to turn on the engine for rewriting URLs.

  RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC]

This line is a condition for the RewriteRule where we match against the HTTP host using a regex pattern. The condition says that if the host is sub.domain.com then execute the rule.

 RewriteRule ^((?!folder).*)$ /folder/$1 [NC,L]

The rule matches http://sub.domain.com/foo and internally redirects it to http://sub.domain.com/folder/foo.

Replace sub.domain.com with your subdomain and folder with name of the folder you want to point your subdomain to.