如何使Apache的mod_rewrite默认通过HTTPSredirect?

假设我有一个通过HTTPS提供的网站,例如https://example.com/foo 。 考虑下面的.htaccess

 RewriteBase / RewriteEngine On RewriteRule ^foo$ bar [R=301,L] 

现在,当我访问https://example.com/foo ,它会通过HTTP而不是HTTPSredirect到http://example.com/bar

我怎样才能使它转到HTTPS而不是使用R标志的每个RewriteRule使用完整的scheme+主机? 也就是说,这会做我以后的事情:

 RewriteBase / RewriteEngine On RewriteRule ^foo$ https://example.com/bar [R=301,L] 

但是,我的.htaccess文件包含许多这样的RewriteRule ,感觉应该有一种方式告诉Apache / mod_rewrite“重写https://默认情况下”。 我真正想要的是告诉Apache网站使用的是HTTPS,类似于通过ServerName foo.ext声明主机名的ServerName foo.ext 。 那可能吗?

我猜这是堆栈溢出类似的问题: 如何说服Apache的原始客户端协议

ServerName接受一个scheme,例如ServerName https://example.com 。 改变这个在configuration和重新启动Apache做的窍门。

从文档 :

有时,服务器运行在处理SSL的设备后面,例如反向代理,负载均衡器或SSL卸载设备。 在这种情况下,请指定https://scheme和客户端在ServerName指令中连接的端口号,以确保服务器生成正确的自引用URL。

这是一个方法来做到这一点:

 RewriteEngine On #redirect all your http trafic to https exept /foo & /bar RewriteCond %{HTTP_HOST} ^example.com RewriteCond %{HTTPS} !=on RewriteCond %{REQUEST_URI} !(/foo|/bar) RewriteRule (.*) https://example.com$1 [R=301,L] #redirect /foo trafic to /bar RewriteCond %{HTTP_HOST} ^example.com RewriteCond %{REQUEST_URI} /foo RewriteRule /foo(.*) http://example.com/bar$1 [R=301,L] 

把它放到你的httpd.conf文件中,或放在你的所有虚拟主机之前,它将被应用到以example.com开始的所有请求(www.example.com不会被redirect)

要将规则应用于所有域,您可以删除行RewriteCond %{HTTP_HOST} ^example.com

有关信息,应尽可能避免使用.htaccess,以防止无用的硬盘访问。

有没有任何理由你不使用普通的Rewrite指令?

 Rewrite / https://example.com/ 

对于子域,你可以做

 Rewrite http://foo.example.com https://foo.example.com