带有 .htaccess 或 PHP 的动态子域页面
Dynamic subdomain pages with .htaccess or PHP
我的目录是这样的:
- /index.php(网站主页)
- /网站
- 站点 1
- 站点 2
- 站点 3
当我转到 site1.example.com
时,我希望它显示 example.com/sites/site1/index.php
当我转到 site1.example.com/page1
时,我希望它显示文件 example.com/sites/site1/page1.php
我该怎么做?谢谢!
我假设您的所有子域都指向与主域相同的位置,因此 subdomain.example.com
和 example.com
指向相同的位置。
在主站点的根目录中的 .htaccess
文件中尝试如下内容:
RewriteEngine On
# Exclude requests for the www subdomain
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ - [L]
# Requests for the site root
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
RewriteRule ^$ sites/%1/index.php [L]
# Requests that are "assumed" to be .php files
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
RewriteRule ^([^.]*)$ sites/%1/.php [L]
# All other requests
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
RewriteRule !^sites/ sites/%1%{REQUEST_URI} [L]
这假定有效的 URL 路径不包含点。
%1
是对 CondPattern(即 子域 )和 </code> 是对 <code>RewriteRule
模式 .
中捕获组的反向引用
但是,您想如何处理非PHP 文件和其他静态资源?
Also, how can I do a 404 page?
您可以定义自定义错误文档。例如:
ErrorDocument 404 /errors/404.php
但是,您需要在 .htaccess
文件的顶部创建一个例外,以防止它被后面的指令重写。例如:
RewriteRule ^errors/ - [L]
您需要:
- 设置一个Wildcard DNS record
- 为您的 .htaccess 编写规则
规则可能如下所示:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com
RewriteRule ^(.*)$ http://example.com/sites/%1/ [L,NC,QSA]
就是这样。
我的目录是这样的:
- /index.php(网站主页)
- /网站
- 站点 1
- 站点 2
- 站点 3
当我转到
site1.example.com
时,我希望它显示example.com/sites/site1/index.php
当我转到
site1.example.com/page1
时,我希望它显示文件example.com/sites/site1/page1.php
我该怎么做?谢谢!
我假设您的所有子域都指向与主域相同的位置,因此 subdomain.example.com
和 example.com
指向相同的位置。
在主站点的根目录中的 .htaccess
文件中尝试如下内容:
RewriteEngine On
# Exclude requests for the www subdomain
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ - [L]
# Requests for the site root
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
RewriteRule ^$ sites/%1/index.php [L]
# Requests that are "assumed" to be .php files
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
RewriteRule ^([^.]*)$ sites/%1/.php [L]
# All other requests
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
RewriteRule !^sites/ sites/%1%{REQUEST_URI} [L]
这假定有效的 URL 路径不包含点。
%1
是对 CondPattern(即 子域 )和 </code> 是对 <code>RewriteRule
模式 .
但是,您想如何处理非PHP 文件和其他静态资源?
Also, how can I do a 404 page?
您可以定义自定义错误文档。例如:
ErrorDocument 404 /errors/404.php
但是,您需要在 .htaccess
文件的顶部创建一个例外,以防止它被后面的指令重写。例如:
RewriteRule ^errors/ - [L]
您需要:
- 设置一个Wildcard DNS record
- 为您的 .htaccess 编写规则
规则可能如下所示:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com
RewriteRule ^(.*)$ http://example.com/sites/%1/ [L,NC,QSA]
就是这样。