环境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]
什么好主意吗?
使用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]
服务器版本:Apache/2.4.29 (Ubuntu)
在网上和apache的官方文档中搜索了很长时间后,唯一适合我的解决方案来自/usr/share/doc/apache2/README.Debian.gz
To enable SSL, type (as user root):
a2ensite default-ssl
a2enmod ssl
在/etc/apache2/sites-available/000-default.conf文件中添加
重定向"/" "https://sub.domain.com/"
<VirtualHost *:80>
#ServerName www.example.com
DocumentRoot /var/www/owncloud
Redirect "/" "https://sub.domain.com/"
就是这样。
注:如果你想阅读手册而不提取:
gunzip -cd /usr/share/doc/apache2/README.Debian.gz
这个代码为我工作。
# ----------port 80----------
RewriteEngine on
# redirect http non-www to https www
RewriteCond %{HTTPS} off
RewriteCond %{SERVER_NAME} =example.com
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
# redirect http www to https www
RewriteCond %{HTTPS} off
RewriteCond %{SERVER_NAME} =www.example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
# ----------port 443----------
RewriteEngine on
# redirect https non-www to https www
RewriteCond %{SERVER_NAME} !^www\.(.*)$ [NC]
RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]