我有这样的目录:
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/$1.php [L]
# All other requests
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com [NC]
RewriteRule !^sites/ sites/%1%{REQUEST_URI} [L]
这假定有效的 URL 路径不包含点。
%1
是对 CondPattern(即子域)和 $1
中捕获的组的反向引用是对 RewriteRule
中捕获的组的反向引用图案。但是,您想如何处理非 PHP 文件和其他静态资源?
Also, how can I do a 404 page?
您可以定义自定义错误文档。例如:
ErrorDocument 404 /errors/404.php
但是,您需要在
.htaccess
的顶部创建一个异常(exception)。文件以防止它被后面的指令重写。例如:RewriteRule ^errors/ - [L]
关于php - 带有 .htaccess 或 PHP 的动态子域页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155932/