Search code examples
.htaccessurl-rewritingsubdomainwildcard-subdomain

htaccess subdomain wildcard to subdirectory single file handler


My website handles every request on the index.php file

https://mywebsite.com/a https://mywebsite.com/a/b

It doesn't matter, https://mywebsite.com/index.php is used. That is done using:

RewriteEngine On
DirectoryIndex index.php

RewriteCond %{REQUEST_URI} !\.(css)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php [L,QSA]

Now, what I want as well is that all subdomains (*) are directed to https://mywebsite.com/*/

So: https://a.mywebsite.com/b/c/d -> https://mywebsite.com/a/b/c/d

I tried adding:

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

But I can't seem to get this to work, neither do I have enough skills to know what I'm doing exactly in this case. Could anyone provide me any tips and explain what is doing what exactly?

My index.phpphp extracts the URL using:

$_SERVER['REQUEST_URI']

Then, I explode all the components into an array with the '/' delimiter. I would then want to obtain an array with ['a', 'b', 'c', 'd'] when I navigate to https://a.mywebsite.com/b/c/d

When I currently implement this, and navigate to https://a.mywebsite.com, I get a "server not found" message (firefox)


Solution

  • The rules you have defined are correct for your purpose. This online service at htaccess.madewithlove.com confirms this, see picture below.

    The issue in your case is that the subdomain a.mywebsite.com is not configured properly. You want to login into your domain registrars' dashboard and create a CNAME record that would point from a.mywebsite.com to mywebsite.com.

    After adding the DNS record and waiting a few hours, you can verify it with dig or some other dns lookup tool or just open the url in a browser.

    It should look like this:

    $ dig a.mywebsite.com @1.1.1.1 CNAME +short 
    mywebsite.com.
    

    The rules are fine (I'm not affiliated with: htaccess.madewithlove.com):

    rule works