简体   繁体   English

如何使用PHP创建子域? 可以在共享主机上吗?

[英]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. 我有兴趣直接从php快速创建子域。 For example when an user create a new page I want that page to be newpage.mydomain.com. 例如,当用户创建新页面时,我希望该页面为newpage.mydomain.com。 Is that possible without changing the php or apache configuration files (supposing I'm using a shared hosting account). 是否可以在不更改php或apache配置文件的情况下(假设我使用的是共享托管帐户)。

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. 在您的.htaccess文件中设置一个错误文档,该文档将每个404重定向到一个可能名为redirection.php的文件。 This .php file is what will handle the "on the fly" redirects. 该.php文件将处理“即时”重定向。

  2. Add a wildcard DNS record in your zone files, so that [whateverhere].yourdomain.com points to the IP of your webserver 在区域文件中添加通配符DNS记录,以便[whateverhere] .yourdomain.com指向您的网络服务器的IP

  3. Add a wildcard serveralias in your apache configs by using: ServerAlias *.yourdomain.com 使用以下命令在您的apache配置中添加通配符serveralias:ServerAlias * .yourdomain.com

  4. Write the following code in your redirection.php file. 在redirection.php文件中编写以下代码。

.

<?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. 您需要确保首先设置一个通配符*在域注册DN面板中针对您的域的记录。

Once you have set up the wildcard, you can just look at the > 设置通配符后,您只需查看>

 $_SERVER["SERVER_NAME"]

it's not possible through php alone. 仅靠PHP是不可能的。 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) 无论如何,因为您必须拥有一个域(或具有编辑DNS记录的权限),然后可以添加通配符记录以允许任何子域指向单个计算机(由其IP地址标识)

edit (from Powerlord comment) 编辑(来自Powerlord的评论)

apache have to redirect each subdomain to the same vhost usually with ServerAlias *.example.com in a vhost configuration apache通常必须在虚拟主机配置中使用ServerAlias *.example.com将每个子域重定向到同一虚拟主机。

/edit /编辑

then in php you can check which from subdomain the page is request by parsing(spliting) $_SERVER['HOST_NAME'] 然后在php中,您可以通过解析(拆分) $_SERVER['HOST_NAME']来检查该页面是从子域请求的

eg: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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