如何自动将子域映射到子文件夹


How to map subdomain to subfolder automatically

我正在使用一个PHP脚本,该脚本在每个用户注册时为每个用户创建一个子文件夹。 例如:domain.com/users/user1

我需要将子域映射到这些子文件夹,例如:user1.domain.com。

我正在使用 XAMPP,我已经遵循了本教程并且效果很好。

但是我必须为每个用户/子域执行此操作!

我需要在用户注册时自动执行此操作。

你想在Apache上进行大规模虚拟主机。在这里,您将找到如何执行此操作的信息:

动态配置的批量虚拟主机

根据您链接的教程中的示例:

NameVirtualHost *
  <VirtualHost *>
    DocumentRoot "C:'xampp'htdocs"
    ServerName localhost
  </VirtualHost>
  <VirtualHost *>
    DocumentRoot "C:'Documents and Settings'Me'My Documents'clientA'website"
    ServerName clientA.local
  <Directory "C:'Documents and Settings'Me'My Documents'clientA'website">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>
<VirtualHost *>
    DocumentRoot "C:'Documents and Settings'Me'My Documents'clientB'website"
    ServerName clientB.local
  <Directory "C:'Documents and Settings'Me'My Documents'clientB'website">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

关于此配置的问题是,它是静态的,您需要在更改它时重新启动 Apache。

首先,您需要在 DNS 服务器中记录将所有子域映射到您的服务器。喜欢这个:

*.local. 3600 IN A x.x.x.x

要在 localhost 上对此进行测试,您可以在hosts文件中手动设置一些子域。请参阅此处为什么无法在hosts文件中设置通配符子域。

不要忘记在 httpd.conf 中加载vhost_alias_module:

LoadModule vhost_alias_module modules/mod_vhost_alias.so

然后,您将替换虚拟主机配置,如以下示例所示:

<VirtualHost *>
    # get the server name from the Host: header
    UseCanonicalName Off
    # this log format can be split per-virtual-host based on the first field
    LogFormat "%V %h %l %u %t '"%r'" %s %b" vcommon
    CustomLog logs/access_log vcommon
    # include the server name in the filenames used to satisfy requests
    VirtualDocumentRoot "C:/Documents and Settings/Me/My Documents/%1/website"
    <Directory "C:/Documents and Settings/Me/My Documents/*/website">
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
        Require all granted
        DirectoryIndex  index.php index.html index.htm
    </Directory>
</VirtualHost>

这将使用通配符来设置所请求的子域的文档根目录。

我通过使用服务器上的默认虚拟主机实现了与此类似的内容。 假设您已经设置了 dns,以便所有子域都指向相应的 IP 地址,那么它们都应该解析为默认虚拟主机。 默认虚拟主机指向的文件夹也需要具有索引.php文件,该文件利用子域来提供适当的内容。

您可以使用 XAMPP 在本地复制此内容,方法是编辑/etc/hosts 文件并将本地 dns 中的子域指向本地主机。 将您的 webroot 设置为索引.php文件所在的位置,并从 $_SERVER 变量中获取域名。 从那里,您可以通过子域确定用户并以编程方式显示内容。

您可以安装像 Plesk 或 Webmin 这样的网络托管控制面板来为您承担这项工作。您将使用友好的GUI来配置子域,所有细节配置都将在后台进行。这就是现实世界的托管服务提供商使用的。

我已经考虑了一段时间,但从未测试过它。我认为你应该尝试与一些MVC框架(如CodeIgniter)相同的方法

使用 index.php 路由所有请求。获取 $_SERVER["HTTP_HOST"] 并解析它以获取您的子域。现在根据您的子域加载相应的视图(在MVC中查看)