使用 .htaccess (PHP) 动态创建子域

发布于 2024-07-14 07:48:20 字数 231 浏览 5 评论 0原文

我希望创建一个系统,在注册时将在我的网站上为用户帐户区域创建一个子域。

例如 johndoe.website.example

我认为这与 .htaccess 文件有关,并可能重定向到网站上的另一个位置? 我其实不知道。 但任何能让我开始的信息将不胜感激。

创建一个注册区域不是问题——我已经做过很多次了。 我只是不确定从哪里开始子域。

I am looking to create a system which on signup will create a subdomain on my website for the users account area.

e.g. johndoe.website.example

I think it would be something to do with the .htaccess file and possibly redirecting to another location on the website? I don't actually know. But any information to start me off would be greatly appreciated.

Creating a sign up area is not the problem - I have done this many a time. I am just unsure where to start with the subdomain.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

东京女 2024-07-21 07:48:20

快速概述

  1. 您需要在 DNS 服务器上创建一个通配符域 *.website.example
  2. 然后在您的虚拟主机容器中,您还需要指定通配符 *.website.example - 这是在 ServerAlias 中完成的DOC
  3. 然后在 PHP 中提取并验证子域并显示相应的数据

长版本

1. 创建通配符 DNS 条目

在您的 DNS 设置中,您需要创建一个 通配符域条目,例如*.example.org。 通配符条目如下所示:

*.example.org.   3600  A  127.0.0.1

2. 在 vhost 中包含通配符

接下来,在 Apache 配置中,您需要设置一个 vhost 容器,该容器在 ServerAlias DOCs 指令。 虚拟主机容器示例:

<VirtualHost *:80>
  ServerName server.example.org
  ServerAlias *.example.org
  UseCanonicalName Off
</VirtualHost>

3. 找出您在 PHP 中所在的子域

然后在 PHP 脚本中,您可以通过查看 $_SERVER 超级全局变量来查找域。 以下是在 PHP 中获取子域的示例:

preg_match('/([^.]+)\.example\.org/', $_SERVER['SERVER_NAME'], $matches);
if(isset($matches[1])) {
    $subdomain = $matches[1];
}

我在这里使用了正则表达式,以允许人们通过 www.subdomain.example.orgsubdomain.example.org 访问您的网站代码>.

如果您从未预料到必须处理 www. (或其他子域),那么您可以简单地使用如下子字符串:

$subdomain = substr(
                 $_SERVER['SERVER_NAME'], 0,
                 strpos($_SERVER['SERVER_NAME'], '.')
             );

Mass Virtual Hosting

Mass Virtual Hosting 与上述方案略有不同,因为您通常会使用它来托管许多不同的网站,而不是尝试使用它为应用程序提供支持正如问题所提出的。

我之前在我的博客上的帖子中记录了我的基于 mod_rewrite 的大规模虚拟托管环境< /a>,如果这是您想要走的路线,您可以查看该路线。 当然,还有相应的 Apache 手册页。

Apache 还有一种处理大规模虚拟主机的内部方法,该方法比我使用的 mod_rewrite 方法稍微不太灵活。 Apache 动态配置的海量虚拟主机手册页。

The quick rundown

  1. You need to create a wildcard domain on your DNS server *.website.example
  2. Then in your vhost container you will need to specify the wildcard as well *.website.example - This is done in the ServerAlias DOCs
  3. Then extract and verify the subdomain in PHP and display the appropriate data

The long version

1. Create a wildcard DNS entry

In your DNS settings you need to create a wildcard domain entry such as *.example.org. A wildcard entry looks like this:

*.example.org.   3600  A  127.0.0.1

2. Include the wildcard in vhost

Next up in the Apache configuration you need to set up a vhost container that specifies the wildcard in the ServerAlias DOCs directive. An example vhost container:

<VirtualHost *:80>
  ServerName server.example.org
  ServerAlias *.example.org
  UseCanonicalName Off
</VirtualHost>

3. Work out which subdomain you are on in PHP

Then in your PHP scripts you can find out the domain by looking in the $_SERVER super global variable. Here is an example of grabbing the subdomain in PHP:

preg_match('/([^.]+)\.example\.org/', $_SERVER['SERVER_NAME'], $matches);
if(isset($matches[1])) {
    $subdomain = $matches[1];
}

I have used regex here to to allow for people hitting your site via www.subdomain.example.org or subdomain.example.org.

If you never anticipate having to deal with www. (or other subdomains) then you could simply use a substring like so:

$subdomain = substr(
                 $_SERVER['SERVER_NAME'], 0,
                 strpos($_SERVER['SERVER_NAME'], '.')
             );

Mass Virtual Hosting

Mass virtual hosting is a slightly different scheme to the above in that you would usually use it to host many distinct websites rather than attempting to use it power an application as the question proposes.

I have documented my mod_rewrite based mass virtual hosting environment before in a post on my blog, which you could look at if that is the route you wish to take. There is also, of course, the respective Apache manual page.

Apache also has an internal way of dealing with mass virtual hosting that is slightly less flexible than the mod_rewrite method I have used. This is all described on the Apache Dynamically Configured Mass Virtual Hosting manual page.

孤千羽 2024-07-21 07:48:20

您可以首先允许每个子域,然后检查子域是否有效。 例如:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$
RewriteRule !^index\.php$ index.php [L]

index.php 中,您可以使用以下方法提取子域:

if (preg_match('/^([^.]+)\.example\.com$/', $_SERVER['HTTP_HOST'], $match)) {
    var_dump($match[1]);
}

但这一切都要求您的网络服务器接受每个子域名。

You could allow every subdomain in the first place and then check if the subdomain is valid. For example:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$
RewriteRule !^index\.php$ index.php [L]

Inside the index.php you can than extract the subdomain using:

if (preg_match('/^([^.]+)\.example\.com$/', $_SERVER['HTTP_HOST'], $match)) {
    var_dump($match[1]);
}

But all this requires that your webserver accepts every subdomain name.

狠疯拽 2024-07-21 07:48:20

除了设置 DNS 通配符之外,您可能还需要查看动态质量Apache 虚拟主机 这就是我过去解决这个问题的方法

In addition to setting up a DNS wildcard, you might want to take a look at Dynamic Mass Virtual Hosting for Apache which is how I've solved this in the past

瞄了个咪的 2024-07-21 07:48:20

我发现使用 PHP 更容易做到这一点。 事实上,就是在 cPanel 中创建一个子域,并在所需的域名下创建您的文件夹。 正如您将在 cPanel 中手动完成的那样,但所有这一切都是通过一个简单的 PHP 函数在几毫秒内完成的。 无需点击:)

function create_subdomain($subDomain,$cPanelUser,$cPanelPass,$rootDomain) {

    //  $buildRequest = "/frontend/x3/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain;

    $buildRequest = "/frontend/x3/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain . "&dir=public_html/subdomains/" . $subDomain;

    $openSocket = fsockopen('localhost',2082);
    if(!$openSocket) {
        return "Socket error";
        exit();
    }

    $authString = $cPanelUser . ":" . $cPanelPass;
    $authPass = base64_encode($authString);
    $buildHeaders  = "GET " . $buildRequest ."\r\n";
    $buildHeaders .= "HTTP/1.0\r\n";
    $buildHeaders .= "Host:localhost\r\n";
    $buildHeaders .= "Authorization: Basic " . $authPass . "\r\n";
    $buildHeaders .= "\r\n";

    fputs($openSocket, $buildHeaders);
        while(!feof($openSocket)) {
           fgets($openSocket,128);
        }
    fclose($openSocket);

    $newDomain = "http://" . $subDomain . "." . $rootDomain . "/";

   //  return "Created subdomain $newDomain";

}

I found it easier doing it with PHP. In fact is creating a subdomain within cPanel and create your folder under the desired domain name. As you will do it manually in cPanel but all it's done in milliseconds by a simple PHP function. No click necessary :)

function create_subdomain($subDomain,$cPanelUser,$cPanelPass,$rootDomain) {

    //  $buildRequest = "/frontend/x3/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain;

    $buildRequest = "/frontend/x3/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain . "&dir=public_html/subdomains/" . $subDomain;

    $openSocket = fsockopen('localhost',2082);
    if(!$openSocket) {
        return "Socket error";
        exit();
    }

    $authString = $cPanelUser . ":" . $cPanelPass;
    $authPass = base64_encode($authString);
    $buildHeaders  = "GET " . $buildRequest ."\r\n";
    $buildHeaders .= "HTTP/1.0\r\n";
    $buildHeaders .= "Host:localhost\r\n";
    $buildHeaders .= "Authorization: Basic " . $authPass . "\r\n";
    $buildHeaders .= "\r\n";

    fputs($openSocket, $buildHeaders);
        while(!feof($openSocket)) {
           fgets($openSocket,128);
        }
    fclose($openSocket);

    $newDomain = "http://" . $subDomain . "." . $rootDomain . "/";

   //  return "Created subdomain $newDomain";

}
眼角的笑意。 2024-07-21 07:48:20

最简单的方法是将所有子域(使用通配符 *)重定向到您的 /wwwroot。
然后使用以下代码将 .htaccess 放入此文件夹:

RewriteCond %{ENV:REDIRECT_SUBDOMAIN} =""
RewriteCond %{HTTP_HOST} ^([a-z0-9][-a-z0-9]+)\.domain\.example\.?(:80)?$ [NC]
RewriteCond %{DOCUMENT_ROOT}/%1 -d
RewriteRule ^(.*) %1/$1 [E=SUBDOMAIN:%1,L]
RewriteRule ^ - [E=SUBDOMAIN:%{ENV:REDIRECT_SUBDOMAIN},L]

这将实现 /wwwroot 文件夹的每个子文件夹都可以通过子域 (foldername.domain.example) 接受。

几年前发现的
http://www.webmasterworld.com/apache/3163397.htm

The easiest way is to redirect all subdomains (with wildcard *) to point to your /wwwroot.
Then put .htaccess to this folder with the following code:

RewriteCond %{ENV:REDIRECT_SUBDOMAIN} =""
RewriteCond %{HTTP_HOST} ^([a-z0-9][-a-z0-9]+)\.domain\.example\.?(:80)?$ [NC]
RewriteCond %{DOCUMENT_ROOT}/%1 -d
RewriteRule ^(.*) %1/$1 [E=SUBDOMAIN:%1,L]
RewriteRule ^ - [E=SUBDOMAIN:%{ENV:REDIRECT_SUBDOMAIN},L]

This will accomplish that every subfolder of the /wwwroot folder in acceptable via subdomain (foldername.domain.example).

Found this years ago on
http://www.webmasterworld.com/apache/3163397.htm

尛丟丟 2024-07-21 07:48:20

这与 .htaccess 无关。 您需要为子域设置 DNS 记录和虚拟托管。

It's nothing to do with .htaccess. You'll need to set up DNS records and virtual hosting for the subdomains.

屌丝范 2024-07-21 07:48:20

Mod_vhost_alias 是执行此操作的正确模块。

只需一行,您就可以告诉 Apache 使用目录散列等方式查看正确的位置。
例如,该行:

VirtualDocumentRoot /http/users/%3.1/%3.2/%3

将告诉 Apache 在请求 subdomain.yourdomain.example 时将文档根设置为 /http/users/s/u/subdomain

Mod_vhost_alias is the right module to do this.

With one line you can tell Apache to look at the right place, with directory hashing, etc.
For example, the line:

VirtualDocumentRoot /http/users/%3.1/%3.2/%3

would tell Apache to set the document root to /http/users/s/u/subdomain when requested for subdomain.yourdomain.example

邮友 2024-07-21 07:48:20

我认为通配符 DNS 与 Apache 的 Dynamic Mass Virtual Hosting 也是一个合理的解决方案。 虽然,我从未尝试过。

如果您需要扩展到多个服务器或其他解决方案不适合您,我建议使用数据库驱动的 DNS 服务器。 我过去曾成功使用过MyDNS。 由于它使用 MySQL(或 PostgreSQL),您可以使用 PHP 或其他任何东西动态更新您的 DNS。 该代码看起来已经有一段时间没有更新了,但它是 DNS,因此并不完全是前沿的。

I think the wild card DNS with Apache's Dynamic Mass Virtual Hosting is a reasonable solution also. Although, I have never tried it.

If you have the need to scale out to multiple servers or the other solutions just don't work for you, I recommend using a database driven DNS server. I have successfully used MyDNS in the past. Since it uses MySQL (or PostgreSQL) you can update your DNS on the fly with PHP or just about anything else. The code doesn't look like it has been updated in a while, but it's DNS and therefore not exactly cutting edge.

独夜无伴 2024-07-21 07:48:20

通配符子域创建方法

首先,您必须使用服务器 DNS 编辑器创建 DNS 设置。

  1. 在 DNS 设置中创建 A 记录,并在服务器 IP 地址中使用主机 * 通配符。

    * 1400 IN A ip_address

  2. 在 DNS 设置中使用主机 @domainname.exampleA 记录服务器 IP 地址中的代码>。 tld 表示顶级域名或域名的扩展名,例如 .com、.org 等...

    @ 1400 IN A ip_address
    或者
    domainname.example 1400 IN A ip_address

  3. 创建CNAME记录,例如:

    www 1400 IN 域名.example

  4. 使用 * 通配符创建子域,例如 *.domainname。示例

  5. *.domainname 的子域目录中创建 .htaccess .example 并输入以下代码:

     选项 +FollowSymLinks 
       重写引擎开启 
       重写库 / 
       RewriteRule ^([aA-zZ0-9]+)$index.php?data=$1 
       RewriteCond %{HTTP_HOST} ^([aA-zZ0-9]+)\.([aA-zZ0-9-]+)\.([aA-zZ]+) 
       RewriteRule ([aA-zZ0-9]+)index.php?data=%1 
      

测试您的第一个通配符子域,如 some.domainname.example

如果您不感兴趣使用 .htaccess 将数据作为参数传递,您还可以使用以下编码获取数据:

define("SUBDOMAIN_PARENT","domainname.example");
class getData
    {
         function __construct()
        {
            $this->data="";
            $http_host=$_SERVER['HTTP_HOST'];
         $subdom_data= str_replace(SUBDOMAIN_PARENT,"",$http_host);
         $expl_subdom_data=explode(".",$subdom_data);
      $expl_subdom_data=array_filter($expl_subdom_data);

            if($expl_subdom_data!=NULL)
            {
           $this->data=end($expl_subdom_data);
            }
       }
    }
$GLOBALS['get_data']=new getData();

并在任何地方使用全局变量,例如 global $get_data

echo $get_data->data; //example

(注意:这个类主要用于从http_host获取准确的子域名。因为在子域名之前组合的一些额外名称也适用,例如www.some.domainname.example。这个return $_GET['data']='wwww' 所以我的建议是使用 $_SERVER['http_host'] 来获取准确的值,而不是使用 < code>$_SERVER['query_string'] 或在索引页中传递 .htaccess 参数)

6. 在 TTL - DNS 设置中使用 N 秒来加快此通配符子域的执行速度。

7.在给定的 ttl 时间(600 - 10 分钟)后检查子域,例如 => http://abc.domainname.example

(注意:通配符子域不会覆盖现有子域。因为第一优先级始终适用于您现有的子域)

Wildcard subdomain creation methods

FIrst you have to create the DNS settings using your server DNS editor.

  1. Create A record in DNS settings with host * wild card in server IP address.

    * 1400 IN A ip_address

  2. Create once again a A record in DNS settings with host @ or domainname.example in server IP address. tld means top level domains or the extension of the domains such as .com, .org, etc....

    @ 1400 IN A ip_address
    or
    domainname.example 1400 IN A ip_address

  3. Create CNAME record like:

    www 1400 IN A domainname.example

  4. Create the subdomain with * wildcard like *.domainname.example

  5. Create .htaccess in your subdomain directory of *.domainname.example and put this code:

     Options +FollowSymLinks
     RewriteEngine On
     RewriteBase /
     RewriteRule ^([aA-zZ0-9]+)$ index.php?data=$1
     RewriteCond %{HTTP_HOST} ^([aA-zZ0-9]+)\.([aA-zZ0-9-]+)\.([aA-zZ]+)
     RewriteRule ([aA-zZ0-9]+) index.php?data=%1
    

Test your first wildcard subdomain like some.domainname.example

If you are not interest to pass the data as parameter using the .htaccess, you can also get the data by using the following coding:

define("SUBDOMAIN_PARENT","domainname.example");
class getData
    {
         function __construct()
        {
            $this->data="";
            $http_host=$_SERVER['HTTP_HOST'];
         $subdom_data= str_replace(SUBDOMAIN_PARENT,"",$http_host);
         $expl_subdom_data=explode(".",$subdom_data);
      $expl_subdom_data=array_filter($expl_subdom_data);

            if($expl_subdom_data!=NULL)
            {
           $this->data=end($expl_subdom_data);
            }
       }
    }
$GLOBALS['get_data']=new getData();

and use your global variable at any place like global $get_data.

echo $get_data->data; //example

(note: This class mainly used for get the exact subdomainname from http_host. because some extra names combined before your subdomain is also applicable like www.some.domainname.example. This return $_GET['data']='wwww' So my suggestion is to use the $_SERVER['http_host'] for get the exact values instead of using the $_SERVER['query_string'] or passed .htaccess parameters in your index page)

6.Speed up the execution of this wildcard subdomains use N seconds in TTL - DNS SETTINGS.

7.Check the subdomain after your given ttl time (600 - 10 minutes) like => http://abc.domainname.example

(note: wildcard subdomains not override the existed subdomains. Because First priority always for your existed subdomains)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文