Search code examples
.htaccessdynamicsubdomain

.htaccess to create dynamic subdomain from subfolder


I wonder how can create a dynamic subdomain pointing to a folder in root when user search for it. Like apples.domain.com pointing to domain.com/apples (apples folder already created manually). Then if the apples folder do not exist, it retrieves a 404. Please, help. I'm such a noob with this topic.


Solution

  • Try:

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com$ [NC]
    RewriteCond %{DOCUMENT_ROOT}/%1 !-d
    RewriteRule ^ - [L,R=404]
    
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com$ [NC]
    RewriteCond %{DOCUMENT_ROOT}/%1 -d
    RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_FILENAME} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ /%1/$1 [L]
    

    in the htaccess file in the domain.com's document root.