简体   繁体   中英

Spring Boot & ELB - How do I make the load balancer redirect http to https?

I have deployed a Spring Boot application via Elastic Beanstalk. I'm using a load balancer, so this is the flow (as far as I understand):

Internet/Browser request ---HTTPS---> Load Balancer ---HTTP---> Spring Boot App Server

So essentially, the SSL terminates at the load balancer and the app server just deals with plain old HTTP.

But in the case of a HTTP request from the browser, I would like the load balancer to automatically redirect to HTTPS.

There are several questions about this issue:

Spring Boot with Embedded Tomcat behind AWS ELB - HTTPS redirect
How to redirect automatically to https with Spring Boot
Spring Boot redirect HTTP to HTTPS

But none of the answers to these questions make sense to me. Perhaps I'm misunderstanding, but all the answers basically make the Spring Boot app only server HTTPS request (for example when using http.requiresChannel().anyRequest().requiresSecure() ).

However, this goes against the flow because I'm perfectly fine with the SSL terminating at the load balancer and the Spring Boot app server just dealing with HTTP. So if I require SSL at the spring boot level, then I'll need to do an end-to-end SSL connection, which isn't really required for my application.

I have also used the following properties, which don't seem to help either:

server.tomcat.remote-ip-header=x-forwarded-for
server.tomcat.protocol-header=x-forwarded-proto  

With the help of this article , I was finally able to figure out how to do this for a Spring Boot app in an ELB environment.

I had to create a conf file in src/main/webapp/.ebextensions/nginx/conf.d . I just called it myconf.conf.

In myconf.conf , I put this code in:

server {
    listen  80;
    server_name www.my-site.com;
    if ($http_x_forwarded_proto != "https") {
        rewrite ^(.*)$ https://$server_name$REQUEST_URI permanent;
    }
}

Also, make sure that both HTTP and HTTPS listeners are open for the load balancer.
Additionally, my spring boot app only opens up HTTP since the load balancer already terminates SSL.

AWS Load Balancers can not send redirects. That is not a feature they have. You have to check the x-forwarded-proto header on the server side, and return a redirect if x-forwarded-proto is http instead of https .

AWS Load balancer cannot handle redirection. You may do it via your server or by using cloudfront distributions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM