Last active
November 20, 2019 15:35
-
-
Save BjoernKW/06a21575dfe702cbef233c2789566a7b to your computer and use it in GitHub Desktop.
http to https redirect with Spring Cloud Gateway
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.bjoernkw.gateway; | |
@Configuration | |
public class HttpToHttpsRedirectConfig { | |
@Value("${server.port}") | |
private Integer gatewayPort; | |
@PostConstruct | |
public WebServerFactoryCustomizer serverFactoryCustomizer() { | |
return new NettyHttpCustomizer(); | |
} | |
private class NettyHttpCustomizer implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> { | |
@Override | |
public void customize(NettyReactiveWebServerFactory httpNettyReactiveWebServerFactory) { | |
httpNettyReactiveWebServerFactory.getWebServer((request, response) -> { | |
URI uri = request.getURI(); | |
URI httpsUri; | |
try { | |
httpsUri = new URI("https", uri.getUserInfo(), uri.getHost(), gatewayPort, 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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment