Search code examples
.htaccessurl-rewriting

Dynamic subdomains using .htaccess


I am developing a multi-vendor shopping cart website in Magento. Currently I have separate url for each vendor like below

http://mydomain.com/vendor1
http://mydomain.com/vendor2

I want to change the above URLs like below

http://vendor1.mydomain.com/
http://vendor2.mydomain.com/

How can I change the URL structure like this using htaccess ?

Any assistance appreciated.


Solution

  • It should look like this:

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /
    
        RewriteRule ^/([^/]+)/(.*)$ http://$1\.example\.com/$2 [R,L]
    </IfModule>
    

    This will rewrite all URLs so that the first subfolder will become the subdomain and the remaining path will slip one folder to the top. The first folder is grabbed by ([^/]+) (which means "all but no slash") and put in the first variable, the rest of the url is grabbed by (.*) and put in the second variable. Which should look like this:

    http://example.com/vendor1/some/path
    

    will become to:

    http://vendor1.example.com/some/path
    

    It's untested, but I hope you get the idea.