Search code examples
.htaccessurl-rewritingwildcard-subdomain

Wildcard Sub-Domain Setup


This works for rewriting all requests to the index.php located in my root folder, which works for example.com/1/2/3/4/5/...

DirectoryIndex index.php
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ / [L]
RewriteCond %{HTTP_HOST} ^((?!www\.)[^.]+)\.mallzones\.com$
RewriteRule (.*) /%{REQUEST_URI}

I am trying to figure how to rewrite the wildcard subdomains as well. The wildcard should be prepended to the path. How do I modify these rules to accomplish the following url scheme.

example.com/1/ is equal to 1.example.com

example.com/1/2 is equal to 1.example.com/2

example.com/1/2/3 is equal to 1.example.com/2/3

example.com/1/2/3/4 is equal to 1.example.com/2/3/4

I've already created the A record in my DNS zones. What do I do next?

ANSWER: kudos to @CRIMSON 501

DirectoryIndex index.php
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ / [L]

Solution

  • Let me understand. Are you asking how to make it so that when a user navigates to example.com/1/ they are rerouted to 1.example.com?

    <IfModule mod_rewrite.c>
    Options +FollowSymLinks
    Options +Indexes
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !www.example.com$ [NC]
    RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-]+).example.com [NC]
    RewriteRule (.*) http://example.com/ [L]
    </IfModule>
    

    To have a silent redirect the last line should be:

    RewriteRule (.*) /index.php/or/whatever/you/need [L]
    

    Just edit the links to what you need!