How To Redirect HTTP To HTTPS On AWS Elastic Load Balancer?

Published September 8, 2024

Problem: Redirecting HTTP to HTTPS on AWS ELB

Redirecting HTTP traffic to HTTPS is important for web application security. When using AWS Elastic Load Balancer (ELB), setting up this redirection can be difficult without the right method.

Solution: Implementing HTTP to HTTPS Redirect on AWS ELB

Using Application Load Balancer for Native Redirection

AWS Application Load Balancer (ALB) has a feature for HTTP to HTTPS redirection. Follow these steps to set up ALB for automatic redirection:

  1. Open the EC2 dashboard and select your Load Balancer.
  2. Click the "Listeners" tab.
  3. Find the HTTP listener and select "View/edit rules".
  4. Remove all rules except the default one.
  5. Edit the default rule: choose "Redirect to" as the action, keep the default settings, and enter "443" as the port.

This method is easy and doesn't need changes to your application code. It works for all your EC2 instances behind the ALB.

Tip: Test Your Redirection

After setting up the redirection rule, test it by accessing your website using HTTP (e.g., http://yourdomain.com). Your browser should automatically redirect to the HTTPS version (https://yourdomain.com). Check the browser's address bar to confirm the secure connection.

Configuring Classic Load Balancer for HTTPS Redirect

For Classic Load Balancer, you have two main options to redirect HTTP to HTTPS:

  1. Server-side redirection: Set up your web server (e.g., NGINX) on each EC2 instance to handle the redirection.
  2. Application-level redirection: Add the redirect logic in your application code.

For NGINX configuration, add this to your server block:

server {
    listen 80;
    server_name yourdomain.com;
    return 301 https://$server_name$request_uri;
}

This NGINX configuration will redirect all HTTP traffic to HTTPS. Update this configuration on all your EC2 instances behind the Classic Load Balancer.

Example: Application-Level Redirection in PHP

<?php
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    $redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header("Location: " . $redirect_url, true, 301);
    exit();
}
?>

This PHP code checks if the current connection is not HTTPS, and if so, redirects to the HTTPS version of the same URL.