Spring cloud gateway 设置https 和http同时支持

              Spring cloud gateway 处理跨域问题

              Spring cloud gateway 拦截请求404 等HTTP 状态码

              Spring cloud gateway 修改response 截断问题,乱码问题解决

              Spring cloud gateway 详解和配置使用(文章较长) 

              Spring cloud Gateway 指定执行过滤器 (在配置文件中配置所需要过滤器)

话不多说,直接上硬货: 

这是gateway 官网的配置截图

   这个配置简单,但是我们需要同时支持http 和https

目前这个问题官方还没有正式解决

https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.2.RELEASE/reference/html/#tls-and-ssl

https://github.com/spring-cloud/spring-cloud-gateway/issues/1103

民间人士,想到的办法是 在启动一个Netty 监听另外一个端口 如:8080,这个端口是不带 s 的也就是   http

当访问8080时 跳转到配置https 的如8443端口 

经过一番查找

https://github.com/spring-projects/spring-boot/issues/12035

https://stackoverflow.com/questions/49045670/spring-webflux-redirect-http-to-https/53000573#53000573

具体实现:

package cn.com.test.gateway.config;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import reactor.core.publisher.Mono;
 
import javax.annotation.PostConstruct;
import java.net.URI;
import java.net.URISyntaxException;

@Configuration
public class HttpToHttpsRedirectConfig {

    @Value("${server.http.port}")
    private int httpPort;
    @Value("${server.port}")
    private int serverPort;

    @PostConstruct
    public void startRedirectServer() {
        NettyReactiveWebServerFactory httpNettyReactiveWebServerFactory = new NettyReactiveWebServerFactory(httpPort);
        httpNettyReactiveWebServerFactory.getWebServer((request, response) -> {
            URI uri = request.getURI();
            URI httpsUri;
            try {
                httpsUri = new URI("https", uri.getUserInfo(), uri.getHost(), serverPort, uri.getPath(), uri.getQuery(), uri.getFragment());
            } catch (URISyntaxException e) {
                return Mono.error(e);
            }
            response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
            response.getHeaders().setLocation(httpsUri);
            return response.setComplete();
        }).start();
    }


}

yml 配置文件配置:

分为俩个端口号,server.port 是配置https 的端口, http.port 是监听的端口

server:
  http:
    port: 4321
  port: 1234
  ssl:
    enabled: true
    key-alias: scg
    key-store: classpath:ssl/test.pfx
    key-store-password: 6540CNd4Whw
    keyStoreType: PKCS12

目录结构: 

 启动后访问,不带s 的4321端口会转发到1234端口。

记得双击摸摸哒!

一键三连摸摸哒!

  • 8
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值