【问题标题】:.htaccess file - Wildcard Subdomains Redirect.htaccess 文件 - 通配符子域重定向
【发布时间】:2015-11-13 11:56:23
【问题描述】:

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

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。有什么想法吗?

谢谢

【问题讨论】:

标签: php apache .htaccess mod-rewrite redirect


【解决方案1】:

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

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]

:-)

【讨论】:

    【解决方案2】:

    首先确保您的 .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]
    

    【讨论】:

      猜你喜欢
      • 2018-08-14
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2019-01-14
      相关资源
      最近更新 更多