Matthew Steven Kelly

HTTPS Apache Redirect using mod_rewrite

February6

This site has a few sections that need to be secure when data is transmitted between the server and local computer. I implement an SSL certificate to accomplish this encryption. However, the issue arose as to how I ensured every time someone visited those pages they were using SSL. If I forgot even a single link to those pages and left the link as http:// instead of https:// users would get to the page unsecured. Additionally a user could always simply manually enter the URL into their web browser’s address bar without the https:// as well. The solution of course is for the web server to detect if the user is viewing the secured page with http:// and redirect them to https:// if they are.

Server Requirements:

  1. Apache web server
  2. Uncomment the mod_rewrite LoadModule call (LoadModule rewrite_module modules/mod_rewrite.so) in the httpd.conf file
  3. Make sure AllowOverride is set to “All” instead of “None” in the Directory section of the httpd.conf file

Since this site is powered using Apache web server I can perform this switch over using mod_rewrite and the .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</IfModule>

All you need to do is create a file called “.htaccess” with the above contents and put it in the directory of your web server you need to switch to SSL (remember that your server must first be configured to use SSL). This is a great feature for webstores, etc. Simply create a directory called “secure”, place all of your web store files in that directory along with the above .htaccess file and you have just ensured your web store is always using encrypted HTTPS communication. The alternative, trying to manage every link into the web store pages, is a nightmare (I’ve done it before).

Take note that since Windows will not allow a file without a name stored on your hard drive, you will need to name the file “htaccess.txt” locally and then rename it after uploading it to the web server using the FTP program used during upload.

posted under Random | No Comments »