Search code examples
phpapache.htaccessmod-rewritesubdomain

.htaccess dynamic subdomains


I’ve been pulling my hair out over this for a while now. I was wondering if there was a way that I could create dynamic subdomains with .htaccess? I’m in a sandbox environment at the minute but I’m looking to do something like this:

awebsite.co.uk -> straight to index.php *.awebsite.co.uk -> straight to init.php

So far, I’ve managed to bodge it and get this done, however, I face a real problem when it comes to params.

*.adomain.co.uk/page throws a 404 or a 500. I’ve bodged it by setting a custom 404 to init.php

The problem I have is I have a rule to hide the .php from the url so adomain.co.uk/apage will display a page.php, but when I try to accomplish the above, this gets messed up. Could anyone point me in the right direction here please? I have a wildcard A record etc. But I can’t set a ServerAlias with my hosting provider.

Many thanks

UPDATE: .htaccess (current)

Options -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

ErrorDocument 404 /sandbox/init.php

Hanlding with PHP should be as easy as

$splitDomain = explode('.', $_SERVER['SERVER_NAME']);
// TODO: remove if not sandbox
$ReqPage = str_replace('/sandbox/', '', $_SERVER['REQUEST_URI']);
//$ReqPage = str_replace('/', '', $_SERVER['REQUEST_URI']);

Solution

  • The default behaviour is to redirect to index.php so you just need to catch non-www subdomains.

    How about:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$   [NC]
    RewriteCond %{HTTP_HOST} !^www\.example\.com$  [NC]
    RewriteRule ^ http://www.example.com/init.php  [L,R]
    

    Or:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$   [NC]
    RewriteCond %{HTTP_HOST} !^www\.example\.com$  [NC]
    RewriteRule ^ init.php  [L]
    

    The first will redirect to init.php (what you asked), the second will call init.php without the redirect (what you meant).