如何使用.htaccess始终将HTTPredirect到HTTPS?

我试图找出答案的几个类似的问题,但到目前为止,我一直没有成功。 请告诉我如何总是将httpredirect到https(并且在进程中从主机名中删除www 。 另外还有一个方面,在主要的Apache conf而不是.htaccess这样做会很好,但是我想这不适用于大多数人。

  • .htaccess使用SSL / HTTPS将wwwredirect到非www
  • 将子域名请求redirect到子目录+ https(使用.htaccess)
  • htaccess的非www的redirecthttp和https

更新:

我已经将这个片段添加到了VirtualHost部分:

 RewriteCond %{HTTP_HOST} ^www\.(.*) RewriteRule ^.*$ https://%1/$1 [R=301,L] 

…但是,当我访问http://www.domain (它应该redirect到https://domain

更新2:

它没有效果,因为我没有使用RewriteEngine on – 所以它现在的作品:

 RewriteEngine on RewriteCond %{HTTP_HOST} ^www\.(.*) RewriteRule ^.*$ https://%1/$1 [R=301,L] 

我不会使用mod_rewrite ,你可以简单地用mod_alias来实现它:

 Redirect permanent / https://other-site 

其中“other-site”是要redirect到的主机名,省略www。 前缀,你不想要的。

有这么多的解决scheme:

 RewriteEngine On RewriteCond %{HTTPS} !^on$ RewriteRule (.*) https://yourdomain/$1 [R,L] 

如果您使用负载平衡器,则需要使用不同的条件。 这适用于AWS ELB:

 <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule (.*) https://yourdomain.com/$1 [R=301,L] </IfModule> 

两个解决scheme 将其中的任何一个添加到您的.htaccess

 RewriteEngine on RewriteCondition %{SERVER_PORT} !^443$ RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L] RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L] 

从你的意见,这听起来像你不包括mod_rewrite:

 LoadModule rewrite_module modules/mod_rewrite.so