简体   繁体   中英

How do you create subdomains using PHP? Is is possible on shared hosting?

I'm interested to create subdomains on the fly directly from php. For example when an user create a new page I want that page to be newpage.mydomain.com. Is that possible without changing the php or apache configuration files (supposing I'm using a shared hosting account).

Later Edit: I'm talking about my domain, and I have full access to the domain administration area.

  1. Set up an error document in your .htaccess file that redirects every single 404 to a file called maybe redirection.php. This .php file is what will handle the "on the fly" redirects.

  2. Add a wildcard DNS record in your zone files, so that [whateverhere].yourdomain.com points to the IP of your webserver

  3. Add a wildcard serveralias in your apache configs by using: ServerAlias *.yourdomain.com

  4. Write the following code in your redirection.php file.

.

<?php

$url = $_SERVER["REQUEST_URL"];
$newurl=str_replace(".yourdomain.com","",$url);
$newcomplete="http://yourdomain.com/".$newurl;
Header("Location: ".$newcomplete);

?>

Does this help a bit?

Yes you can do this. You need to make sure that first you set up a wildcard * A record against your domain in your domain register DN panel.

Once you have set up the wildcard, you can just look at the >

 $_SERVER["SERVER_NAME"]

it's not possible through php alone. and I don't think shared hosting allow that. anyway, for that you have to own a domain (or have permission to edit DNS record) then you can add wildcard record to allow any subdomain to point to a single machine (identified by its IP adress)

edit (from Powerlord comment)

apache have to redirect each subdomain to the same vhost usually with ServerAlias *.example.com in a vhost configuration

/edit

then in php you can check which from subdomain the page is request by parsing(spliting) $_SERVER['HOST_NAME']

eg:

$host = explode ('.', $_SERVER['HOST_NAME']);
array_pop ($host);
array_pop ($host);
$subdomain = join ('.', $host);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM