Search code examples
apache.htaccesshttp-status-code-403

Why are our dynamic subdomains returning a 403 forbidden error when accessed?


We are trying to make subdomains attached to their directory counterparts with the same name, so we have done this with our .htaccess

php_value session.cookie_domain .domain.com

RewriteEngine on
RewriteCond %{HTTP_HOST} ^([^/.]+)\.domain\.com$ 
RewriteCond %1 !^(www|ftp|mail)$ [NC]
RewriteRule (.+)$ "http://domain.com/%0" [L,P]


DirectoryIndex index.php

to make an attempt to access a subdomain, direct the user to the directory. But our problem is everytime we try to access ANY subdomain, we get a 403. We're using Apache on Debian. Wildcard in DNS working, but don't know how to specify it within the Virtual Host.


Solution

  • You can put this code in your htaccess (which has to be in document root folder)

    php_value session.cookie_domain .domain.com
    DirectoryIndex index.php
    
    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} ^(.+?)\.domain\.com$ [NC]
    RewriteCond %1 !^(?:www|ftp|mail)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ /%1/$1 [L]
    

    This code will internally rewrite every subdomain (except www, ftp and mail) to its subfolder equivalent.

    Example: http://user.domain.com/something will be internally rewritten to /user/something

    Note: make sure wildcard is pointing to the same document root as main domain