Code前端首页关于Code前端联系我们

HTTP重定向到HTTPS、IIS7和APACHE实现及nginx配置

terry 2年前 (2023-09-28) 阅读数 56 #未命名
如何在IIS7和Apache上实现HTTP访问转HTTPS访问。网站设计出于安全考虑应该使用https协议,但是很多用户因为不喜欢使用https协议而输入URL,导致访问异常。因此,我需要一个重定向功能来实现将HTTP网站重定向到HTTPS网站的方法。具体操作如下

IIS7

从微软官网下载HTTP Redirect编写模块,安装完成后重启IIS服务,然后打开IIS控制台发现多了一个组件。双击“重写URL”,在相应的表单中选择“添加规则”并添加一个空行以自定义规则。一个名称(名称可选),比如我称之为“重定向到HTTPS”,模式为:(.*),添加一个条件,条件条目为{HTTPS},匹配模式,模式为^OFF $ 然后配置操作。操作类型为:重定向,重定向URL为:https://{HTTP_HOST}/{R:1},重定向类型:永久301。

设置完成后,点击右侧“应用”,重写网址已配置。

配置完成后,根文件夹下的web.config文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="redirect to HTTPS" enabled="true" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="^OFF$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Apache http跳转到https配置

更改.htaccess文件,在文件中添加以下几行:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

另一种写法是:

RewriteEngine on
RewriteBase /
RewriteCond %{SERVER_PORT} !^443$
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R=301,L]

nginx配置

nginx重写方法

思考

这应该是任何人都能想出的最简单的方法了。只需通过rewrite将所有http请求重写为https即可

配置

server { 
  listen 192.168.1.111:80; 
  server_name test.com; 
   
  rewrite ^(.*)$ https://$host$1 permanent; 
} 

搭建好这个虚拟主机后,就可以将所有从http://test.com的请求重写为https://test.com

nginx的497状态code

错误代码 497

497 - 正常请求发送到 HTTPS

说明:当此虚拟站点只允许 https 访问时,通过 http 访问时 nginx 会报告 497 错误代码

想法

使用error_page 命令将状态码为 497 的链接重定向到 https://test 在域名 .com 上配置

server {
Listen 192.168.1.11:443; #ssl端口
监听192.168.1.11:80; #用户习惯使用http访问,后面加80通过。 497状态码导致其自动跳转到端口443
服务器名称test.com;
#启用服务器的ssl支持{...}
ssl on;
#指定PEM格式证书文件
ssl_certificate /etc/nginx/test.pem;
#指定PEM格式的私钥文件
ssl_certificate_key /etc/nginx/test . key;

#将http请求重定向到https请求
error_page 497 https://$host$uri?$args;
}

index.html 刷新页面

思路
以上两种方式都会消耗服务器资源。我们来尝试使用curl访问baidu.com,看看百度公司是如何实现baidu.com到www.baidu.com的跳转

可以看到,百度巧妙地利用了meta的刷新功能,实现了baidu.com到www.baidu.com的跳转。百度.com。因此,我们也可以根据http://test.com的虚拟主机路径编写一个index.html,内容将是http方向。 https跳转

index.html



nginx虚拟主机配置

server {
listen 192.168.1.11:80;
服务器名称test.com;

location/{
#index.html放在虚拟主机上Listen 在根目录下
root /srv/www/http.test.com/;
}
#将404页面重定向到https主页
error_page 404 https://test.com/ ;
}

Postscript
以上三种方法都可以用来基于nginx将http请求强制转换为https请求。您可以根据实际需要评估利弊或做出选择。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

热门