个人随笔
目录
springboot重定向自动跳转到了http怎么解决?
2022-09-15 10:45:16

背景

因为我们的项目一直用的都是http,后面公司决定改为https,并且把80端口给封了,这简单,我们只需要简单的申请个证书,然后nginx简单的配置下即可。

问题

当我们在nginx配置好,进入网站登录页面,输入用户密码登录后,突然变成了http?这什么鬼?调试看下发现springboot进行重定向后竟然变成了http,纳尼!!!

难道springboot重定向后会自动变为http?

解决方案

上网百度了下,发现真的很多人遇到这个问题

也就是springboot的这种写法,会自动变为http的

  1. return "redirect:index"

那看看别人的解决方案

1、nginx对80端口做转发即可

这种解决方案应该是很大一部分人的解决方案,毕竟有些用户可能还是习惯用http,然后我们只需要做个转发即可,配置如下

  1. server {
  2. listen 80;
  3. server_name suibibk.com www.suibibk.com;
  4. rewrite ^(.*)$ https://www.suibibk.com$1 permanent;
  5. }

简单方便,也不怕用户访问http的请求,一股脑转发到https即可。

我的博客项目用的就是这种方案。

2、nginx和springboot配合修改

Nginx修改

  1. proxy_set_header Host $host;
  2. proxy_set_header X-Real-IP $remote_addr;
  3. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  4. proxy_set_header X-Forwarded-Proto $scheme;
  5. proxy_pass http://127.0.0.1:8080;
  6. #proxy_redirect http:// https://;

Springboot启动类修改

  1. @Bean
  2. public EmbeddedServletContainerFactory servletContainer(){
  3. TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
  4. factory.setUriEncoding(Charset.forName("UTF-8"));
  5. RemoteIpValve value = new RemoteIpValve();
  6. value.setRemoteIpHeader("X-Forwarded-For");
  7. value.setProtocolHeader("X-Forwarded-Proto");
  8. value.setProtocolHeaderHttpsValue("https");
  9. factory.addEngineValves(value);
  10. return factory;
  11. }

若是war包则在tomcat的在server.xml的Engine模块下面配置多一个以下的Valve

  1. <Valve className="org.apache.catalina.valves.RemoteIpValve"
  2. remoteIpHeader="X-Forwarded-For"
  3. protocolHeader="X-Forwarded-Proto"
  4. protocolHeaderHttpsValue="https"/>

这种没有试过,还要nginx配合,我觉得太麻烦了。可能也很有效。

3、弃用springboot的重定向语法,直接使用response.sendRedirect(…)

当我们是要封禁80端口后,第一种,第二种方案就不科学了,那么我们可以直接指定重定向的地址,而不是用springboot的redirect语法,毕竟一个项目中也就重定向的地方也不会太多。

  1. return "redirect:index"

改为

  1. try{
  2. response.sendRedirect("https://请求地址");
  3. }catch(IOException e){
  4. }
  5. return null;

注意后面一定要返回null,而不能还是写为redirect:index不然可能会报如下错误

  1. java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

也不能写"",我的项目写""后触发了无限循环,导致内存溢出了。

我们测试一下,可以看到Location就直接改变了。

总结

其实最简单的就是方案1,直接nginx配置个转发就好了。如果直接不能使用80,那么可以采取方案3.方案3的本质其实就是改变Location,告知浏览器直接重定向到哪个请求。

 1873

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2