环境Centos与apache

试图设置自动重定向从http到https

From manage.mydomain.com --- To ---> https://manage.mydomain.com 

我已经尝试添加以下到我的httpd.conf,但它没有工作

 RewriteEngine on
    ReWriteCond %{SERVER_PORT} !^443$
    RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]

什么好主意吗?


当前回答

我实际上遵循了这个例子,它对我很有效:)

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName mysite.example.com
   Redirect permanent / https://mysite.example.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  SSLEngine On
 # etc...
</VirtualHost>

然后做:

/etc/init.d/httpd restart

其他回答

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}

http://www.sslshopper.com/apache-redirect-http-to-https.html

or

http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html

实际上,你的主题属于https://serverfault.com/,但你仍然可以尝试检查这些.htaccess指令:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1

使用mod_rewrite不是推荐的方式,而是使用虚拟主机和重定向。

如果你倾向于使用mod_rewrite:

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same 
location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in
# httpd.conf or .htaccess context

参考:Httpd Wiki -重写httptohttps

如果你正在寻找一个301永久重定向,那么重定向标志应该是,

 R=301

所以RewriteRule会像这样,

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]

我实际上遵循了这个例子,它对我很有效:)

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName mysite.example.com
   Redirect permanent / https://mysite.example.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  SSLEngine On
 # etc...
</VirtualHost>

然后做:

/etc/init.d/httpd restart

我需要这个来做一些简单的事情,比如将所有http流量从我服务器上的默认apache主页重定向到一个通过https服务的页面。

由于我在配置apache时仍然很绿色,我更倾向于避免直接使用mod_rewrite,而是使用像这样更简单的东西:

<VirtualHost *:80>
  <Location "/">
     Redirect permanent "https://%{HTTP_HOST}%{REQUEST_URI}"
  </Location>
</VirtualHost>

<VirtualHost *:443>
  DocumentRoot "/var/www/html"
  SSLEngine on
  ...
</VirtualHost>

我喜欢这个,因为它允许我使用apache变量,这样我就不必指定实际的主机名,因为它只是一个没有关联域名的IP地址。

引用: https://stackoverflow.com/a/40291044/2089675