0

我試圖在我的應用程序中實現HTTPS。它是一個在端口8080上運行的JHipster/SpringBoot應用程序。我通過AWS實現了HTTPS,使事情變得更加簡單,因爲證書可以由AWS證書管理器服務自動處理/續訂。AWS EC2將HTTP重定向到HTTPS槽負載平衡器

所以我沒有改變我的服務器上的任何東西。我在AWS上生成了一個證書,並將LoadBalancer規則配置爲使用生成的證書從443重定向到8080。當我嘗試使用明確的HTTPS訪問我的域時,它就像一個魅力。

問題是我也想重定向HTTP訪問到HTTPS,然後我試圖添加一個規則重定向80到443,所以它會落入第一條規則(443到8080)並使用證書,但它不起作用。在網上研究我發現我應該添加一些行到我的.htacess文件,但不起作用。我認爲這不是我的解決方案,因爲所有HTTPS的東西都在AWS端,是否有一種方法可以通過AWS將HTTP重定向到HTTPS而無需更改我的服務器?

回答

1

您需要將HTTPS重定向的HTTP流量作爲應用程序的一部分,並且需要適應必要的規則和配置。

例如,你會如果使用與打開ELB端口80(HTTP),這將通過Web服務器80或任何端口監聽執行重定向[單獨的偵聽]

處理開始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

答案以上沒有工作對我來說,因爲我沒有用這樣的文件。我最終做這樣一個後端過濾器:

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); 
    } 
} 
相關問題