How to create a subdomain with username as subdomain name? - php

I have referred other related question but they are not clear to me. Please explain me: How can I make subdomain in PHP?
Example :
http://www.domainname.com/page.php?usname=sundar
I want change the link to this
http://sundar.domainname.com
Is this possible in PHP? Or any other way to do it?

You may create a virtual sub domains and then you can redirect it with .htaccess.
You also have to create
A Record look like this
*.exmple.com A 127.0.0.1 or your IP
in your DNS.
Then add something like this in your .htaccess
RewriteRule ^([aA-zZ])$ home.php?username=$1
RewriteCond %{HTTP_HOST} ^(^.).mywebsite.com
RewriteRule (.) home.php?username=%1
It should help

my way:
you will have to create a wildcard subdomain and point it you your domain.
http://www.easymodrewrite.com/example-subdomains
Then you can parse $_SERVER['HTTP_HOST'] for querying out the user name .
if you are under hosting plane, you can probably create it from the GUI.
Else, you need to via the APACHE panel and configure the DNS.

You could use .htaccess url rewrite to make that.
Just rewrite www.(username).site.com to www.site.com/profile/(username)
the code for that would be something like..
RewriteRule ^(.*).site.nl site.nl/profile/$1
if my memory serves me right

Related

How to add a subdomain for every user that registers with PHP on Apache? [duplicate]

How do I create subdomain like http://user.mywebsite.example? Do I have to access .htaccess somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?
To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?
You're looking to create a custom A record.
I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:
*.mywebsite.example IN A 127.0.0.1
127.0.0.1 would be the IP address of your webserver. The method of actually adding the record will depend on your host.
Then you need to configure your web-server to serve all subdomains.
Nginx: server_name .mywebsite.example
Apache: ServerAlias *.mywebsite.example
Regarding .htaccess, you don't really need any rewrite rules. The HTTP_HOST header is available in PHP as well, so you can get it already, like
$username = strtok($_SERVER['HTTP_HOST'], ".");
If you don't have access to DNS/web-server config, doing it like http://mywebsite.example/user would be a lot easier to set up if it's an option.
The feature you are after is called Wildcard Subdomains. It allows you not have to setup DNS for each subdomain, and instead use Apache rewrites for the redirection. You can find a nice tutorial here, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:
<VirtualHost 111.22.33.55>
DocumentRoot /www/subdomain
ServerName www.domain.example
ServerAlias *.domain.example
</VirtualHost>
However as it required the use of VirtualHosts it must be set in the server's httpd.conf file, instead of a local .htaccess.
I do it a little different from Mark. I pass the entire domain and grab the subdomain in PHP.
RewriteCond {REQUEST_URI} !\.(png|gif|jpg)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}
This ignores images and maps everything else to my index.php file. So if I go to
http://fred.mywebsite.example/album/Dance/now
I get back
http://fred.mywebsite.example/index.php?uri=album/Dance/now&hostName=fred.mywebsite.example
Then in my index.php code I just explode my username off of the hostName. This gives me nice pretty SEO URLs.
We setup wildcard DNS like they explained above. So the a record is *.yourname.example
Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.
We use the following code:
$url=$_SERVER["REQUEST_URI"];
$account=str_replace(".yourdomain.com","",$url);
This code just sets the $account variable the same as the subdomain. You could then retrieve their files and other information based on their account.
This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited .htaccess this method should work (as long as your host will setup the wildcard for you).
We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.
Don't fuss around with .htaccess files when you can use [Apache mass virtual hosting][1].
From the documentation:
#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs
In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.
The only drawback is that the environment variable DOCUMENT_ROOT is not correctly set to the used subdirectory, but the default document_root in de htconfig.
[1]: http://httpd.apache.org/docs/2.0/vhosts/mass.html
Simple PHP solution for subdomains and multi-domain web apps
Step 1. Provide DNS A record as "*" for domains (or domain) you gonna serve example.org
A record => *.example.org
A record => *.example.net
Step 2. Check uniquity of logins when user registering or changing login.
Also, avoid dots in those logins.
Step 3. Then check the query
<?php
// Request was http://qwerty.example.org
$q = explode('.', $_SERVER['HTTP_HOST']);
/*
We get following array
Array
(
[0] => qwerty
[1] => example
[2] => org
)
*/
// Step 4.
// If second piece of array exists, request was for
// SUBDOMAIN which is stored in zero-piece $q[0]
// otherwise it was for DOMAIN
if(isset($q[2])) {
// Find stuff in database for login $q[0] or here it is "qwerty"
// Use $q[1] to check which domain is asked if u serve multiple domains
}
?>
This solution may serve different domains
qwerty.example.org
qwerty.example.net
johnsmith.somecompany.example
paulsmith.somecompany.example
If you need same nicks on different domains served differently,
you may need to store user choise for domain when registering login.
smith.example.org // Show info about John Smith
smith.example.net // Show info about Paul Smith
In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.
Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.
You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.
This can be achieved in .htaccess provided your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named * and specifying a folder called subdomains as the document root for wildcard subdomains. Add this to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.example$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.example$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]
Finally, create a folder for your subdomain and place the subdomains files.
I just wanted to add, that if you use CloudFlare (free), you can use their API to manage your dns with ease.
You can accomplish this via two steps.
Setup wildcard subdomain
Get the subdomain entered by user
Validate the subdomain
1. Setup wildcard subdomain
This might vary depending on your hosting provider. I use Namecheap.com, and the process was as simple as follows
go to cPanel
go to sub domains
enter "*" as the value of subdomain
Now every time you enter a random string before your domain name, it will direct to the wildcard sub domain. You can modify the contents of this wildcard subdomain.
2. Get the subdomain entered by user
You can now add a php file in the wildcard directory in file manager.
<?php
$link = $_SERVER['HTTP_HOST'];
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Wildcard Subdomain</title>
</head>
<body>
<h1>The visitor went to
<?php
echo "<br>";
print("link is: ".$link);
print("<br><br>");
echo "actual file: ".$actual_link;
?>
</h1>
</body>
</html>
3. Validate the subdomain
You might want to validate the sub domain to check if there is some user linked to it. This can be done with a check to a database.
Create Dynamic Subdomains using PHP and .htaccess
#(1) Root .htaccess
This file is redirection http://www.yourwebsite.example to http://yourwebsite.example for home page use. All of the subdomain redirection to yourwebsite_folder
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.yourwebsite.example
RewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^yourwebsite\.example $
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1
#(2) Inside Folder .htaccess
This file is rewriting the subdomain URLs.
http://yourwebsite.example/index.php?siteName=9lessons
to
http://9lessons.yourwebsite.example
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteRule (.*) index.php?siteName=%1
More .htaccess tips: Htaccess File Tutorial and Tips.
#index.php
This file contains simple PHP code, using regular expressions validating the subdomain value.
<?php
$siteName='';
if($_GET['siteName'] )
{
$sitePostName=$_GET['siteName'];
$siteNameCheck = preg_match('~^[A-Za-z0-9_]{3,20}$~i', $sitePostName);
if($siteNameCheck)
{
//Do something. Eg: Connect database and validate the siteName.
}
else
{
header("Location: http://yourwebsite.example/404.php");
}
}
?>
//HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Project Title</title>
</head>
<body>
<?php if($siteNameCheck) { ?>
//Home Page
<?php } else { ?>
//Redirect to Subdomain Page.
<?php } ?>
</body>
</html>
#No Subdomain Folder
If you are using root directory(htdocs/public_html) as a project directory, use this following .htaccess file.
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourwebsite.example
RewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]
RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteRule (.*) index.php?siteName=%1

.htaccess Rewrite "external" subdomain to subfolder if match

Lets say i have wildcard subdomains on an external domain, can be anything like
demo.site1.com
blah.site1.com
and have directories like these on an external websites
external.com/websites/demo.site1.com
external.com/websites/blah.site1.com
and i want to make it so that all requests for lets say demo.site1.com should rewrite to
external.com/websites/demo.site1.com if the subdirectory matches demo.site1.com
NO REDIRECTION, I MUST KEEP THE URL THE SAME...
I have to do this for multiple subdomains with the same kind of subdirectories.
Is it possible to do?? if not is it possible without matching???
I read the apache .htaccess docs over and over for the past 12 hours and can't seem to
figure out a way how to do it.
Your help will mean alot to me...
You should configure Your domain in domain administration panel to point at this addresses.
If You don't have access to them use iframe, but as far I know .htaccess doesn't provide this kind of functionality.
try this. put it inside htaccess on site1.com document root. it work only if both domain has permission to access together
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.*)\.site1.com/(.*)$
RewriteRule ^(.*)$ external.com/websites/$1.site1.com/$2 [L]

htaccess "faking subdomains"

I've been looking at htaccess and how to use rewrite rules in order to make a sort of "fake subdomain" for users.
so far i have:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([a-z0-9-]+)/? http://$1.domain.com [R=301,NC,L]
RewriteCond %{HTTP_HOST} ^([a-z]+)\.domain\.com$
RewriteRule ^$ index.php?user=%1
this will take any /somthing and make it a subdomain and then pass the subdomain value in as a param to pick up.
i want to be able to now use actual parameters, and pass them through normaly with the extra "user" param from the "subdomain"
e.g.
fred.domain.com/index.php?page=1&sort=up
would give me in $_GET
['user'] = 'fred'
['page']= 1
['sort'] = up
but for the life of me I cant figure out how to do this! as when i add any other params, I loose the user bit
Any help? =)
Also any helpful tutorials on htaccess would be nice! as all ones ive found haven't really explained what each bit does and why =\
Thanks in advance
.htaccess file has nothing to do here. It can't help you.
To direct a user to your server, you have to alter DNS record, not web-server config.
I am assuming that:
You own a domain, domain.com say, that is being hosted by some shared hosting service (SHS) provider.
You either have access to a control panel to set up subdomains, or your SHS provider has already set up a * A record mapping to its shared service.
Some SHS providers simply map *.domain.com to a fixed subdirectory, say /webroot/domain.com/public_html; others do this top level-redirection for their users and provide a control panel which allow account-holders to associate subdomains with specific subdirectories.
So you need to work out which applies in your case:
by looking at your SHS providers FAQs,
by trying http://sss.domain.com/ to see if it routes to your DOCROOT
by using a phpinfo() script to see what Rewrite environment variable it uses to point to your DOCROOT. (For technical reasons in Apache, see Dynamic mass virtual hosts with mod_rewrite, %{DOCUMENT_ROOT} cannot be properly initialised for each user, so providers typically use a RewriteMap to initialise a stand-in; mine uses %{ENV:DOCUMENT_ROOT_REAL})
So let's assume that you want to set up a blog at say http://blog.domain.com/, you may need to:
Issue permanent redirects [R=301] from legacy references to http://domain.com/blog/* to http://blog.domain.com/*
Issue internal redirects from http://blog.domain.com/* to DOCROOT/blogdir/*
Add the necessary conditional interlocks to prevent infinite redirection loops, where this second internal redirect is then treated as a legacy reference.
I could give you a set of rewrite rules to do this, but given that I've answered a dozen flavours of this same Q this months, you can find lots of templates by searching or by looking at my blog (Webfusion, .htaccess) where I've written a number of articles giving more explanation.
If you want a single application to catch some wildcard subset of domain, as long as you can encode this in a regexp then you can do something like:
RewriteCond %{HTTP_HOST} (sompattern)\.domain\.com
RewriteRule ^(?!appdir/).* appdir/catchall.php?arg=$0&subdomain=%1 [L,QSA]
The (?!appdir/) bit is called a lookahead negative assertion and this stops the rule refiring on itself.
I'm pretty sure you can set vhost *.yourdomain.com to point to a single path and then use mod_rewrite for the url parsing.

How to build a subdomain from script

In my project I have to make a subdomain, i.e
if the user name is XXX when he register, a sub domain will be created like XXX.example.com
how to do it?
I will use php for scripting.
I found a script that seems to do exactly that, create a subdomain on your server on demand.
It probably needs a little bit of tweaking for it to work on your particular control panel, but the review are quite positive as far as I can tell.
Link
Have you considered using htaccess and url rewriting?
Found this code that may help you:
# Rewrite <subdomain>.example.com/<path> to example.com/<subdomain>/<path>
#
# Skip rewrite if no hostname or if subdomain is www
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
# Extract (required) subdomain (%1), and first path element (%3), discard port number if present (%2)
RewriteCond %{HTTP_HOST}<>%{REQUEST_URI} ^([^.]+)\.example\.com(:80)?<>/([^/]*) [NC]
# Rewrite only when subdomain not equal to first path element (prevents mod_rewrite recursion)
RewriteCond %1<>%3 !^(.*)<>\1$ [NC]
# Rewrite to /subdomain/path
RewriteRule ^(.*) /%1/$1 [L]
Source (Post #6)
This might be a little more complex than you think.
I suggest to do some reading on mod rewriting and htaccess.
You could start here:
htaccess Tutorial
Modrewrite tutorial
Subdomain Modrewrite Example
EDIT: Or just go with one of the nice examples provided my fellow SO users. ;)
As long as this is for non-SSL sites, then by far the easiest way is not to bother - just use a wildcard DNS domain and vhost, then map any domain specific behaviours in your PHP code. If you need SSL sites then its a lot more complicated - you need to have a seperate IP address/port for each certificate - and woldcard certs can be very expensive.
If you're wanting to set up some sort of hosting package then its a bit more involved - how you go about this depends on what webserver and DNS server you are using.
Assuming (again no SSL) with Apache on Unix/POSIX/Linux and bind, then, again I'd go with a wildcard DNS entry, then:
1) create a base dir for the website, optionally populate this with a default set of files
2) add a vhost definition in its own file in /etc/httpd/conf.d named as XXX.conf
3) send a kill -HUP to the HTTPD process (causes it to read the new config files without having to do a full restart).
One thing to note is that you really shouldn't allow the httpd process direct write access to its own config files - you definitely don't want to give it root privileges. A safer solution would be to create a CLI script to perform this using the username as an argument then make it setuid and invoke it from the script run by the HTTPD process.
C.
the best way is to use a joker in your DNS server :
www.example.com. IN A 1.2.3.4
*.example.com. IN A 1.2.3.4
By this way, No subdomain has to be created : all are pointing to the same IP by default.
In your PHP code, you just have get $_SERVER["HOST"] and get the fist part :
$hostParts=explode('.',$_SERVER["HTTP_HOST"]);
$user=$hostParts[0]
First, you need to make sure you have a wildcard domain setup in DNS, and make sure your webserver (apache?) directs all queries for that wildcard domain to your php file.
Then in php you can look at $_SERVER["HTTP_HOST"] to see which subdomain is used for that particular request.
Since you will make sub-domains when an user registers.
Try this as .htaccess file:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^.htaccess$ - [f]
RewriteCond %{HTTP_HOST}!^www.domain.com
RewriteCond %{HTTP_HOST} ^([^.]+).domain.com
RewriteRule ^$(.*) /$1/%1 [L]
make a function of a controller which will take the value of sub-domain and display what necessary.
like::
public function show ($domain)
{
**.**..*..**.** Your code goes here
}
when a user will try this xxx.domain.com/controller/show this will be domain.com/controller/show/xxx . if you want to xxx.domain.com to be domain.com/controller/show/xxx just edit the htaccess file as you want.

How to let PHP to create subdomain automatically for each user?

How do I create subdomain like http://user.mywebsite.example? Do I have to access .htaccess somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?
To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?
You're looking to create a custom A record.
I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:
*.mywebsite.example IN A 127.0.0.1
127.0.0.1 would be the IP address of your webserver. The method of actually adding the record will depend on your host.
Then you need to configure your web-server to serve all subdomains.
Nginx: server_name .mywebsite.example
Apache: ServerAlias *.mywebsite.example
Regarding .htaccess, you don't really need any rewrite rules. The HTTP_HOST header is available in PHP as well, so you can get it already, like
$username = strtok($_SERVER['HTTP_HOST'], ".");
If you don't have access to DNS/web-server config, doing it like http://mywebsite.example/user would be a lot easier to set up if it's an option.
The feature you are after is called Wildcard Subdomains. It allows you not have to setup DNS for each subdomain, and instead use Apache rewrites for the redirection. You can find a nice tutorial here, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:
<VirtualHost 111.22.33.55>
DocumentRoot /www/subdomain
ServerName www.domain.example
ServerAlias *.domain.example
</VirtualHost>
However as it required the use of VirtualHosts it must be set in the server's httpd.conf file, instead of a local .htaccess.
I do it a little different from Mark. I pass the entire domain and grab the subdomain in PHP.
RewriteCond {REQUEST_URI} !\.(png|gif|jpg)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}
This ignores images and maps everything else to my index.php file. So if I go to
http://fred.mywebsite.example/album/Dance/now
I get back
http://fred.mywebsite.example/index.php?uri=album/Dance/now&hostName=fred.mywebsite.example
Then in my index.php code I just explode my username off of the hostName. This gives me nice pretty SEO URLs.
We setup wildcard DNS like they explained above. So the a record is *.yourname.example
Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.
We use the following code:
$url=$_SERVER["REQUEST_URI"];
$account=str_replace(".yourdomain.com","",$url);
This code just sets the $account variable the same as the subdomain. You could then retrieve their files and other information based on their account.
This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited .htaccess this method should work (as long as your host will setup the wildcard for you).
We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.
Don't fuss around with .htaccess files when you can use [Apache mass virtual hosting][1].
From the documentation:
#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs
In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.
The only drawback is that the environment variable DOCUMENT_ROOT is not correctly set to the used subdirectory, but the default document_root in de htconfig.
[1]: http://httpd.apache.org/docs/2.0/vhosts/mass.html
Simple PHP solution for subdomains and multi-domain web apps
Step 1. Provide DNS A record as "*" for domains (or domain) you gonna serve example.org
A record => *.example.org
A record => *.example.net
Step 2. Check uniquity of logins when user registering or changing login.
Also, avoid dots in those logins.
Step 3. Then check the query
<?php
// Request was http://qwerty.example.org
$q = explode('.', $_SERVER['HTTP_HOST']);
/*
We get following array
Array
(
[0] => qwerty
[1] => example
[2] => org
)
*/
// Step 4.
// If second piece of array exists, request was for
// SUBDOMAIN which is stored in zero-piece $q[0]
// otherwise it was for DOMAIN
if(isset($q[2])) {
// Find stuff in database for login $q[0] or here it is "qwerty"
// Use $q[1] to check which domain is asked if u serve multiple domains
}
?>
This solution may serve different domains
qwerty.example.org
qwerty.example.net
johnsmith.somecompany.example
paulsmith.somecompany.example
If you need same nicks on different domains served differently,
you may need to store user choise for domain when registering login.
smith.example.org // Show info about John Smith
smith.example.net // Show info about Paul Smith
In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.
Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.
You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.
This can be achieved in .htaccess provided your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named * and specifying a folder called subdomains as the document root for wildcard subdomains. Add this to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.example$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.example$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]
Finally, create a folder for your subdomain and place the subdomains files.
I just wanted to add, that if you use CloudFlare (free), you can use their API to manage your dns with ease.
You can accomplish this via two steps.
Setup wildcard subdomain
Get the subdomain entered by user
Validate the subdomain
1. Setup wildcard subdomain
This might vary depending on your hosting provider. I use Namecheap.com, and the process was as simple as follows
go to cPanel
go to sub domains
enter "*" as the value of subdomain
Now every time you enter a random string before your domain name, it will direct to the wildcard sub domain. You can modify the contents of this wildcard subdomain.
2. Get the subdomain entered by user
You can now add a php file in the wildcard directory in file manager.
<?php
$link = $_SERVER['HTTP_HOST'];
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Wildcard Subdomain</title>
</head>
<body>
<h1>The visitor went to
<?php
echo "<br>";
print("link is: ".$link);
print("<br><br>");
echo "actual file: ".$actual_link;
?>
</h1>
</body>
</html>
3. Validate the subdomain
You might want to validate the sub domain to check if there is some user linked to it. This can be done with a check to a database.
Create Dynamic Subdomains using PHP and .htaccess
#(1) Root .htaccess
This file is redirection http://www.yourwebsite.example to http://yourwebsite.example for home page use. All of the subdomain redirection to yourwebsite_folder
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.yourwebsite.example
RewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^yourwebsite\.example $
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1
#(2) Inside Folder .htaccess
This file is rewriting the subdomain URLs.
http://yourwebsite.example/index.php?siteName=9lessons
to
http://9lessons.yourwebsite.example
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteRule (.*) index.php?siteName=%1
More .htaccess tips: Htaccess File Tutorial and Tips.
#index.php
This file contains simple PHP code, using regular expressions validating the subdomain value.
<?php
$siteName='';
if($_GET['siteName'] )
{
$sitePostName=$_GET['siteName'];
$siteNameCheck = preg_match('~^[A-Za-z0-9_]{3,20}$~i', $sitePostName);
if($siteNameCheck)
{
//Do something. Eg: Connect database and validate the siteName.
}
else
{
header("Location: http://yourwebsite.example/404.php");
}
}
?>
//HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Project Title</title>
</head>
<body>
<?php if($siteNameCheck) { ?>
//Home Page
<?php } else { ?>
//Redirect to Subdomain Page.
<?php } ?>
</body>
</html>
#No Subdomain Folder
If you are using root directory(htdocs/public_html) as a project directory, use this following .htaccess file.
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourwebsite.example
RewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]
RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteRule (.*) index.php?siteName=%1

Categories