Springboot以Tomcat为容器实现http重定向到https的两种方式

本文介绍了Springboot结合Tomcat如何实现http到https的重定向,包括通过Container Factory和Spring Security两种方式。重定向的主要目的是确保用户安全访问,通过配置不同端口和使用特定组件来实现。
摘要由CSDN通过智能技术生成

1 简介

本文将介绍在 Springboot 中如何通过代码实现 Http 到 Https 的重定向,本文仅讲解Tomcat 作为容器的情况,其它容器将在以后一一道来。

建议阅读之前的相关文章:

(1) Springboot整合https原来这么简单

(2) HTTPS之密钥知识与密钥工具Keytool和Keystore-Explorer

2 相关概念

2.1 什么叫重定向

所谓重定向,就是本来你想浏览地址A的,但是到达服务端后,服务端认为地址A的界面不在了或者你没权限访问等原因,不想你访问地址A;就告诉你另一个地址B,然后你再去访问地址B。

对于重定向一般有两个返回码:

  • 301:永久性重定向;
  • 302:暂时性重定向。

通过 Chrome 查看网络详情,记录了几个网站的重定向情况:

网站 域名 重定向代码 重定向后的网址
南瓜慢说 www.pkslow.com 301 https://www.pkslow.com
Google www.google.com 307 https://www.google.com
Apple www.apple.com 307 https://www.apple.com
支付宝 www.alipay.com 301 https://www.alipay.com
QQ www.qq.com 302 https://www.qq.com
百度 www.baidu.com 307 https://www.baidu.com

注:307也是重定向的一种,是新的状态码。

2.2 为什么要重定向

结合我上面特意列的表格,是不是大概想到了为何要做这种重定向?不难发现上面的重定向都在做一件事,就是把 http 重定向为 https 。原因如下:

(1) http 是不安全的,应该使用安全的 https

Springboot可以通过配置Tomcat实现重定向https。具体实现方式如下:在application.properties文件中添加以下配置: ``` server.port=80 server.ssl.key-store=classpath:keystore.p12 server.ssl.key-store-password=your_password server.ssl.keyStoreType=PKCS12 server.ssl.keyAlias=tomcat server.ssl.enabled=true server.tomcat.remote-ip-header=x-forwarded-for server.tomcat.protocol-header=x-forwarded-proto ``` 其中,server.port设置为80,表示http协议的端口;server.ssl.enabled设置为true,表示启用https协议;server.ssl.key-store设置为证书的路径;server.ssl.key-store-password设置为证书的密码;server.ssl.keyStoreType设置为证书的类型;server.ssl.keyAlias设置为证书的别名。最后,在Springboot的启动类中添加如下代码: ``` @Bean public TomcatServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; tomcat.addAdditionalTomcatConnectors(httpConnector()); return tomcat; } @Bean public Connector httpConnector() { Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL); connector.setScheme("http"); connector.setPort(80); connector.setSecure(false); connector.setRedirectPort(443); return connector; } ``` 这段代码的作用是将http请求重定向https请求。其中,httpConnector()方法返回一个Connector对象,设置了http协议的端口为80,https协议的端口为443,以及重定向的设置。servletContainer()方法返回一个TomcatServletWebServerFactory对象,设置了安全约束,以及添加了httpConnector()方法返回的Connector对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值