Using .htaccess to Redirect to an SSL Connection

I've been doing work for a client needing part of their site to be protected by SSL. All traffic to that section needed to be routed through a secure (https) connection. Unexpectedly I found a solution for ensuring this that was so simple, I had to post it here.

The best way to reroute a client if you are on an Apache server is to set up a mod_rewrite in a .htaccess file. Without going into all the boring details, I'll jump straight to the good stuff.

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

That's right, just three simple lines. The first tells Apache that we are doing a mod_rewrite, or redirecting URLs that match the following pattern. The second line checks if the client is connecting over an unsecured connection. If they are, then the third line redirects them through a SSL connection.

The real power in this is how general it is. Since everything is done using global variables, you can use it on any domain you want without having to change a thing. Simply place it in the folder you want and it will reroute all traffic there through SSL. This works no matter what port your SSL connection is using. If you want the entire site to be secure, just place it in your root folder.

.htaccess files only work on Apache servers. If your site is not hosted using an Apache server, this won't help you much.

Pretty slick stuff. Too bad I can't take any credit for it. Here is where I first came across it. Redirect To SSL Using Apache’s .htaccess

If you'd like to learn more, here are some great tutorials on .htaccess.

This entry was posted in PHP, Tips and tagged , , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post.