.htaccess 重定向 URL 但不是子域的内容

.htaccess redirecting URL but not content for subdomain

我正在尝试建立一个测试站点,但在 .htaccess 正确重定向时遇到了真正的麻烦。

我希望 www.example.com/test 的内容在用户输入 test.example.com 时显示。我的重写规则允许我在地址栏中使用 test.example.com,但它实际上显示的是根目录 (www.example.com) 的内容,而不是 test 子文件夹。

无论如何我都不是 .htaccess 大师,但我已经使用 Stack Overflow 5 年了,这是我第一次被难倒到可以问问题!感谢您的集体智慧。

这是我的 .htaccess 代码的相关部分:

RewriteEngine On

# Rewrite for http cases
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

# Rewrite for no www cases
RewriteCond %{HTTP_HOST} !www\.example\.com [NC]

#redirect for test subdomain
RewriteCond %{HTTP_HOST} !^test\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/ [R=301,L]

# redirect to correct for old subfolder usage
RewriteRule ^oldsubfolder/$ https://www.example.com/ [L,R=301]

I want the contents of www.example.com/test to show when a user types in test.site.com.

我假设你只有一个域,test.site.com 应该是 test.example.com(这似乎与你的问题的其余部分一致)?

在您发布的代码中,没有真正尝试执行此重定向的内容?在您发布的代码中,对 test.example.com 的请求不会被重定向 - 因此如果是,那么您可能会看到缓存的响应。清除浏览器缓存。

你需要这样的东西:

RewriteCond %{HTTP_HOST} ^(?:www\.)?(test)\.example\.com [NC]
RewriteRule (.*) http://www.example.com/%1/ [R,L]

(?:www\.)? 部分只是捕获子域的可选 www 子域!根据此子域的创建方式,test.example.comwww.test.example.com 都可以访问。 (虽然我怀疑你的 SSL 证书可能不允许这样做?)

%1 是对 CondPattern(即 test)中捕获组的反向引用,</code> 是对捕获的 <code>RewriteRule 的反向引用模式。捕获子域(例如 "test")只是避免了重复,而且还允许多个子域由同一规则处理。

这也是一个临时 (302) 重定向。仅当您确定它正在工作时(如果这是意图)将其更改为 301。默认缓存 301,因此会使测试出现问题。

测试前清除浏览器缓存。


# Rewrite for no www cases
RewriteCond %{HTTP_HOST} !www\.example\.com [NC]

#redirect for test subdomain
RewriteCond %{HTTP_HOST} !^test\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/ [R=301,L]

此块中间的注释似乎具有误导性(它不会 "redirect for test subdomain")。整个块只是重定向到 www,不包括 test 子域。其他代码然后重定向子域。


更新:

I was hoping it would continue to show test.example.com in the address bar

是的,这是可能的。如果 test.example.comwww.example.com 指向相同的文件系统,那么您可以简单地 重写 请求而无需实际更改主机。对于这个例子,我假设 test.example.comwww.example.com 指向同一个文档根目录。

把上面的redirect改成下面的rewrite:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^(?:www\.)?(test)\.example\.com [NC]
RewriteRule (.*) /%1/ [L]

请求现在停留在 test.example.com 并将提供来自 test.example.com/test 的内容(尽管这对用户是隐藏的)因为 test.example.comwww.example.com 实际上是相同的

针对 REDIRECT_STATUS 的检查确保我们只处理初始请求而不是重写的请求,从而避免重写循环。 REDIRECT_STATUS 在初始请求中为空,并在第一次成功重写后设置为 200

但是,如果 test.example.com 指向完全不同的地方,那么您将需要实施反向代理和 "proxy" 对 www.example.com 的请求,以便 "hide"来自用户。