繁体   English   中英

.htaccess 文件 - 通配符子域重定向

[英].htaccess file - Wildcard Subdomains Redirect

我有很多使用通配符配置的子域,例如

subdomain1.domain.com
subdomain2.domain.com
subdomain3.domain.com
(...)
subdomain89.domain.com

等等等等

它们指向 /public_html/。 在我创建的 public_html 里面

/public_html/subdomain1
/public_html/subdomain2
/public_html/subdomain3
(..)
/public_html/subdomain89

子文件夹。

我想将来自子域(任何)的所有请求重定向到相应子文件夹中的 index.php 文件,例如:

http://subdomain1.domain.com/
http://subdomain1.domain.com/about_us.php
http://subdomain1.domain.com/contact.php

重定向到 /public_html/subdomain1/index.php。

http://subdomain2.domain.com/
http://subdomain2.domain.com/about_us.php
http://subdomain2.domain.com/contact.php

重定向到 /public_html/subdomain2/index.php 等。

这是我的.htaccess:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-]+)\.domain\.com$ [NC]
RewriteRule !^([a-z0-9-]+)($|/) /%2%{REQUEST_URI}/index.php [PT,L]

当我访问 subdomain1.domain.com 时,我看到来自 /public_html/subdomain1 的 index.php 文件,但是当我访问 subdomain1.domain.com/about_us.php 时,我得到了 404。有什么想法吗?

谢谢

我已经想通了。 这是工作代码:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-]+)\.domain\.com$ [NC]
RewriteRule !^([a-z0-9-]+)($|/) /%2%{REQUEST_URI}/ [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

:-)

首先确保您的 .htaccess 文件位于您的文档根目录(与 index.php 相同的位置),否则它只会影响它所在的​​子文件夹(以及其中的任何子文件夹 - 递归)。

接下来对您的规则稍作更改,使其看起来像:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

目前你只是在匹配上。 这是任何字符的一个实例,您至少需要 .* 来匹配任何字符的任意数量的实例。

$_GET['path'] 变量将包含假目录结构,例如 /mvc/module/test,然后您可以在 index.php 中使用它来确定您想要执行的控制器和操作。

如果您希望将整个 shebang 安装在子目录中,例如 /mvc/ 或 /framework/ 最简单的方法是稍微更改重写规则以将其考虑在内。

RewriteRule ^(.*)$ /mvc/index.php?path=$1 [NC,L,QSA]

并确保您的 index.php 位于该文件夹中,而 .htaccess 文件位于文档根目录中。

$_GET['path'] 的替代方案(更新于 2018 年 2 月和 19 年 1 月)

将路径设置为 $_GET 变量实际上并不是必需的(现在甚至不常见),许多框架将依赖 $_SERVER['REQUEST_URI'] 来检索相同的信息 - 通常是确定使用哪个控制器 - 但原则是完全相同的。

这确实稍微简化了 RewriteRule,因为您不需要创建路径参数(这意味着 OP 的原始 RewriteRule 现在将起作用):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]

但是,关于在子​​目录中安装的规则仍然适用,例如

RewriteRule ^.*$ /mvc/index.php [L,QSA]

暂无
暂无

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

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