.htaccess 将 http 重定向到 https [英] .htaccess redirect http to https

查看:59
本文介绍了.htaccess 将 http 重定向到 https的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧网址 (www1.test.net),我想将其重定向到 https://www1.test.net
我已经在我的网站上实施并安装了我们的 SSL 证书.
这是我的旧文件 .htaccess:

I have an old url (www1.test.net) and I would like to redirect it to https://www1.test.net
I have implemented and installed our SSL certificate on my site.
This is my old file .htaccess:

RewriteEngine On
RewriteRule !\.(js|gif|jpg|png|css|txt)$ public/index.php [L]
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ public/$1 [L]

如何配置我的 .htaccess 文件,以便 url 自动重定向到 https?
谢谢!

How can I configure my .htaccess file so that url auto redirect to https?
Thanks!

推荐答案

2016 年更新

由于这个答案受到了一些关注,我想提示一种更推荐的使用虚拟主机执行此操作的方法:Apache:重定向 SSL

As this answer receives some attention, I want to hint to a more recommended way on doing this using Virtual Hosts: Apache: Redirect SSL

<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>

旧答案,老掉牙的东西鉴于您的 ssl-port 未设置为 80,这将起作用:

Old answer, hacky thing given that your ssl-port is not set to 80, this will work:

RewriteEngine on

# force ssl
RewriteCond     %{SERVER_PORT} ^80$
RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

请注意,这应该是您的第一个重写规则.

Note that this should be your first rewrite rule.

此代码执行以下操作.RewriteCond(ition) 检查请求的 ServerPort 是否为 80(这是默认的 http 端口,如果您指定了另一个端口,则必须对其进行调整).如果是这样,我们匹配整个 url (.*) 并将其重定向到 https-url.%{SERVER_NAME} 可以替换为特定的 url,但这样您就不必更改其他项目的代码.%{REQUEST_URI} 是 TLD(顶级域)之后的 url 部分,因此您将被重定向到您来自的位置,但作为 https.

This code does the following. The RewriteCond(ition) checks wether the ServerPort of the request is 80 (which is the default http-port, if you specified another port, you would have to adjust the condition to it). If so, we match the whole url (.*) and redirect it to a https-url. %{SERVER_NAME} may be replaced with a specific url, but this way you don't have to alter the code for other projects. %{REQUEST_URI} is the portion of the url after the TLD (top-level-domain), so you will be redirected to where you came from, but as https.

这篇关于.htaccess 将 http 重定向到 https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆