Redirect HTTP traffic to HTTPS with Apache
Occasionally when I am setting up a web server I want all interaction to occur in a secure channel encrypted with SSL. I like to leave standard HTTP access available so that the standard http:// url still brings you to the proper site, so I redirect HTTP traffic on port 80 to an HTTPS session on port 443. Since I only do this once in a while, I always have to go searching for the proper method to do it, so I’m posting it here for a quick reference and to share it around.
The way to direct HTTP traffic to HTTPS is with the mod_rewrite URL Rewriting Engine module in Apache. Here is the process that I used earlier today on an Ubuntu 8.04 Server with Apache2.
First enable the rewrite module using the a2enmod utility:
$ sudo a2enmod rewrite
Next edit /etc/apache2/sites-available/default to redirect the port 80 virtual host to the port 443 virtual host.
$ sudo vi /etc/apache2/sites-available/default
<VirtualHost *:80>
RewriteEngine on
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^(.*)$ https://%{SERVER_NAME}$1 [R,L]
. . .
</VirtualHost>
RewriteEngine on enables mod_rewrite on this virtual host. RewriteCond %{SERVER_PORT} ^80$ matches all requests on port 80, then RewriteRule ^(.*)$ https://%{SERVER_NAME}$1 [R,L] rewrites the request making it an https:// request. Now all requests coming in on port 80 (HTTPS) will be redirected to port 443 (HTTPS).
Now save em>/etc/apache2/sites-available/default and reload the Apache configuration to make the rewrite active.
$ sudo /etc/init.d/apache2 reload
For more information regarding Apache mod_rewrite or more details related to the rewrite rules structure and regular expressions see the documentation.