【发布时间】:2017-04-22 12:08:55
【问题描述】:
我被困在使用 htaccess 重定向,混合了一些关于 htaccess 重定向的答案 [1] [2]。
我的目标是将每个子域(不是 www)重定向到我的主域(以 https://www. 开头),保持 Request_URI(如指定文件夹)不变。
这是我所做的:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.mydomain\.fr$ [NC]
# OR : RewriteCond .* ^(.+)\.%{HTTP_HOST}%{REQUEST_URI}$ [NC]
RewriteCond %{HTTP_HOST} !^www\.mydomain\.fr$ [NC]
RewriteRule ^ https://www.mydomain.fr%{REQUEST_URI} [L,R=301,QSA]
这个配置做重定向(强文本是错误的重定向):
- test.mydomain.fr => https://www.mydomain.fr
- test.mydomain.fr/foo => https://www.mydomain.fr/foo
- mydomain.fr => https://www.mydomain.fr
- https://foo.mydomain.fr => https://foo.mydomain.fr
- www.mydomain.fr => http://www.mydomain.fr
交换
RewriteCond %{HTTP_HOST} !^www\.mydomain\.fr$ [NC]
到
RewriteCond %{HTTP_HOST} !^https://www\.mydomain\.fr [NC] 给了我一个重定向错误的错误。
我的想法是检查 HTTP_HOST 的格式是否为https://www.mydomain,如果没有重定向到带有请求信息的好 URL
RewriteRule ^ https://www.mydomain.fr/%{REQUEST_URI}
为什么会有错误的重定向? 我是否必须编写 2 组 Condition 和 Rule 来首先检查子域,然后是 HTTPS ? (我目前正在尝试使用一个规则和多个条件进行重定向,这可能不是最佳做法)
编辑:我的目标是进行这些重定向:
- test.mydomain.fr => https://www.mydomain.fr
- test.mydomain.fr/foo => https://www.mydomain.fr/foo
- mydomain.fr => https://www.mydomain.fr
- https://foo.mydomain.fr => https://www.mydomain.fr
- www.mydomain.fr => https://www.mydomain.fr
提前感谢任何答案/想法。
编辑 2:
我已经在THIS 问题上尝试了 Larzan 的答案,它似乎做了我想做的事情,除了一件事:如果我在浏览器中的 URL 类似于 https://foobar.mydomain.fr,浏览器会向我显示一个关于安全,我必须接受风险,然后重定向到https://www.mydomain.fr。如何删除此警告?
#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.mydomain
RewriteRule ^(.*)$ https://www.mydomain.fr%{REQUEST_URI} [L,R=301]
#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
【问题讨论】:
-
https://foo.mydomain.fr => https://foo.mydomain.fr是什么意思?两个 URL 相同,什么都没有发生? -
我已经编辑了我的问题以添加我想要的重定向。 @DusanBajic:我想禁止子域 foo。
-
@anubhava : 我想通过 httpS 而不是 http
-
stackoverflow.com/questions/37286178/… ,你需要有通配符证书
-
好的,所以我需要更多的步骤来实现我想要的。谢谢你的回答!
标签: apache .htaccess redirect mod-rewrite