AWS EC2通过负载均衡器将HTTP重定向到HTTPS

时间:2016-10-10 17:20:32

标签: amazon-web-services https spring-boot elastic-load-balancer aws-certificate-manager

我试图在我的应用程序中实现HTTPS。它是一个在端口8080上运行的JHipster / SpringBoot应用程序。我通过AWS实现了HTTPS,使事情更容易,因为证书可以由AWS证书管理器服务自动处理/更新。

所以我在服务器上没有改变任何东西。我在AWS上生成了证书,并使用生成的证书将LoadBalancer规则配置为从443重定向到8080。当我尝试使用显式HTTPS访问我的域时,它就像一个魅力。

问题是我还想将HTTP访问重定向到HTTPS,然后我尝试添加一个规则来重定向80到443,所以它将属于第一个规则(443到8080)并使用证书,但它不起作用。在线研究我发现我应该在我的.htacess文件中添加一些行,但也不起作用。我认为这不是我的解决方案,因为所有的HTTPS内容都在AWS端,有没有办法只通过AWS将HTTP重定向到HTTPS而不更改我的服务器?

2 个答案:

答案 0 :(得分:1)

您需要将HTTP流量视为HTTPS重定向,也是应用程序的一部分,并且需要适应必要的规则和配置。

例如,您将首先打开PORT 80(HTTP)的ELB,这将由在80或任何端口监听的Web服务器处理以执行重定向[单独的侦听器]

如果您使用的是Apache Web服务器,则需要使用

等规则
<VirtualHost *:80>
...
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI}
...
</VirtualHost>

参考:

  1. http://www.emind.co/how-to/how-to-force-https-behind-aws-elb/
  2. Rerouting all http traffic to https with AWS ELB

答案 1 :(得分:1)

上面的答案对我没有用,因为我没有使用这样的文件。我最终做了一个这样的BackEnd过滤器:

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HttpToHttpsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
        // Nothing to destroy
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String protocol = httpRequest.getHeader("X-Forwarded-Proto");
        if (protocol != null) {
            if(protocol.toLowerCase().equals("https")) {
                httpResponse.setHeader("Strict-Transport-Security", "max-age=60");
            }
            else if(protocol.toLowerCase().equals("http")) {
                String host = httpRequest.getServerName();
                String requestURI = httpRequest.getRequestURI();
                String redirectUrl = "https://" + host + requestURI;
                httpResponse.sendRedirect(redirectUrl);
                return;
            }
        }

        chain.doFilter(request, response);
    }
}
相关问题