Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic subdomain using PHP and htaccess?

Tags:

php

.htaccess

I have one problem: I want to set up PHP and htaccess to make dynamic subdomains. And I can not figure out how. Currently my URL looks like this:

www.exemple.com/index.php?subdomain=mike&component=content&id=26&title=people-love-apps 

I need it to look like this:

www.mike.exemple.com/content/26/people-love-apps.html

I know it can be done but I do not know a solution how to do it. Is very important to me with $ _GET [] functions to read parameter in the URL.

The problem is that users on my site make their web site and get a free domain (sub-domain) automatically. This should be automatic.

Thanks!

like image 584
Ivijan Stefan Stipić Avatar asked Jul 17 '13 17:07

Ivijan Stefan Stipić


2 Answers

You can't make dynamic subdomains with .htaccess

You will need to configure the apache virtual host to accept requests for multiple domains

See the Apache documentation - Using Name Based Virtual Hosts

<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com *.example.com
    DocumentRoot /www/domain
</VirtualHost>

Adding the wildcard subdomain *.example.com, your PHP application will receive all requests for any domain below example.com, ie garbage.example.com, busted.example.com, llama.example.com, etc.

Creating Wildcard Sub Domain Using Apache VirtualHost

Multiple Domains to One Virtual Host | Wildcard Host (shared hosting)?

Apache default virtual host for multiple domains

At this point, your application will have to determine the validity of the subdomain and display the appropriate error for unknown subs.

From there, parse the domain for mike.

like image 146
user20232359723568423357842364 Avatar answered Oct 18 '22 12:10

user20232359723568423357842364


OF COURSE you can interprete dynamic subdomains with htaccess. The following rule will solve the problem.

RewriteCond %{HTTP_HOST} www\.([^.]+)\.example\.com [NC]
RewriteRule ^/content/([0-9]+)/([a-zA-Z0-9_\-])\.html /index.php?subdomain=%1&component=content&id=$1&title=$2  [L]

so anyone visting

 www.mike.exemple.com/content/26/people-love-apps.html

will see the content of

www.exemple.com/index.php?subdomain=mike&component=content&id=26&title=people-love-apps 
like image 22
tormuto Avatar answered Oct 18 '22 13:10

tormuto