Search code examples
springamazon-web-serviceshttp-redirecthttpsebextensions

Http to Https AWS Elasticbeanstalk


I am using AWS Elasticbeanstalk for my Spring MVC web application. I want to redirect all the request to https. I tried following this How to force https on elastic beanstalk? but this didn't work for me. This code redirects to https but my app didn't work. It shows "This page isn’t working". Code for your reference

<VirtualHost *:80>
  RewriteEngine on
  RewriteCond %{HTTP:X-Forwarded-Proto} =http
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  <Proxy *>
    Order Allow,Deny
    Allow from all
  </Proxy>
  ProxyPass / http://localhost:8080/ retry=0
  ProxyPassReverse / http://localhost:8080/
  ProxyPreserveHost on

  ErrorLog /var/log/httpd/elasticbeanstalk-error_log
</VirtualHost>

Solution

  • Assuming you've already tested HTTPS working fine when your website is visited with HTTPS already. If not you can add this file .ebextensions/loadbalancer-terminatehttps.config with content as below:

    option_settings:
      aws:elb:listener:443:
        ListenerProtocol: HTTPS
        SSLCertificateId: arn:aws:acm:us-west-2:<your-account-id>:certificate/<certificate-arn-on-aws-acm>
        InstancePort: 80
        InstanceProtocol: HTTP
    

    All what's left is to configure the instances Apache config to redirect the clients visiting your website with HTTP to HTTPS, add the code below to a new file .ebextensions/001_ssl_rewrite.config

    Apache 2.4+

    files:
        "/etc/httpd/conf.d/ssl_rewrite.conf":
            mode: "000644"
            owner: root
            group: root
            content: |
                RewriteEngine On
                <If "-n '%{HTTP:X-Forwarded-Proto}' && %{HTTP:X-Forwarded-Proto} != 'https'">
                RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
                </If>
    

    Apache 2.2.X

    files:
        "/etc/httpd/conf.d/ssl_rewrite.conf":
            mode: "000644"
            owner: root
            group: root
            content: |
                LoadModule rewrite_module modules/mod_rewrite.so
                RewriteEngine On
                # This will enable the Rewrite capabilities
                RewriteCond %{HTTPS} !=on
                # This checks to make sure the connection is not already HTTPS
                RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
    

    You can check which Apache is installed on your Elastic Beanstalk from here

    For more, please read both of those answers: https://stackoverflow.com/a/38751749/1772245 and https://stackoverflow.com/a/40670047/1772245