HowTo: Forcing traffic to https

Here I consider two cases for forcing all the traffic to https and I assume you are using Apache Webserver.

Case A) Without LoadBalancer
Suppose you are running a site without a load balancer. Add these lines to your Apache configuration file:

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Suppose you have Virtualhost entries for Http (port 80) and Https (port 443) then add this to VirtualHost entry of Http.

Case B) With LoadBalancer
Consider a scenario where you have a Loadbalancer and the communication between loadbalancer and server takes place like this:
1. When a request comes on port 80 of the loadbalancer it communicates with server on port 80 (i.e. LB Port 80 ==> Server Port 80)
2. And when a request comes on port 443 of the loadbalancer it communicates with server on port 80 (i.e. LB Port 443 ==> Server Port 80)

Here servers are always working on port 80.

If you are using Apache as a LoadBalancer you need to add this to the VirtualHost entry of https:

RequestHeader set X-Forwarded-Proto "https"

On the server add this to the VirtualHost entry of http:

RewriteEngine On

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

This will forward all the incoming requests on http to https.

This also works with Amazon’s Elastic Load Balancer as it has a support for X-Forwarded-Proto and X-Forwarded-Port.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s