Search code examples
apacheamazon-web-servicesmod-rewriteamazon-elastic-beanstalkgoogle-openid

mod_rewrite - Port 80 does not change to 443 when HTTP is explicitly requested


I have an app deployed to Elastic Beanstalk whose Tomcat container uses Google OpenID Connect for authentication. I want to redirect all http requests to https, for which I have the following mod_rewrite configuration in a file in .ebextensions -

files:
    "/etc/httpd/conf.d/ssl_rewrite.conf":
        mode: "000644"
        owner: root
        group: root
        content: |
            LoadModule rewrite_module modules/mod_rewrite.so
            RewriteEngine On
            RewriteCond %{HTTP:X-Forwarded-Proto} =http
            RewriteRule . https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

Google OAuth2 credentials console has https://example.com/j_security_check as an authorized redirect URL. The configuration works fine when either example.com or https://example.com is requested, whereupon the app is redirected to the mentioned authorized URL.

However, when http is explicitly requested - http://example.com - the app is being redirected to https but port 80 is still being used. The authorized redirect URL then becomes https://example.com:80/j_security_check and I get Error: redirect_uri_mismatch.

How can I redirect explicit http requests to https with the port changed to 443? The main goal is to match the mentioned authorized redirect URL. If possible, I'd like to implement this with the .ebextensions configuration file or a similar solution.


Solution

  • The problem was not with the rewrite rule. The file had to be placed in a specific path within .ebextensions for it to work in Tomcat 8. The configuration files had to be setup differently too. Most examples provided were not for Tomcat so I ended up putting them in the wrong location.

    What worked -

    In /.ebextensions/httpd/conf.d/myconf.conf, place -

    LoadModule rewrite_module modules/mod_rewrite.so
    

    and in /.ebextensions/httpd/conf.d/elasticbeanstalk/00_application.conf, place -

    <VirtualHost *:80>
      <Proxy *:80>
        Order Allow,Deny
        Allow from all
      </Proxy>
      ProxyPass / http://localhost:8080/ retry=0
      ProxyPassReverse / http://localhost:8080/
      ProxyPreserveHost on
    
      RewriteEngine On
      RewriteCond %{HTTP:X-Forwarded-Proto} =http
      RewriteRule . https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
    
      ErrorLog /var/log/httpd/elasticbeanstalk-error_log
    </VirtualHost>
    

    Take note of the use of .conf files instead of .config. This is important!

    Also, the redirection that I was getting was not genuine. I was not paying close attention, because when I requested example.com, the browser cache was serving me https://example.com. It was not actually redirecting an http request to https.