8.4. Forcing a Secure Connection

Problem

You need to make sure that pages and forms that handle your visitors' confidential information are transmitted over a SSL connection between their browsers and your web server.

Solution

Use an Apache mod_rewrite rule in an .htaccess file to check the connection type, and switch to a secure connection before the page is returned to the visitor's browser:

	RewriteEngine On
	RewriteCond %{SERVER_PORT} !443$
	RewriteRule ^(.*)$ https://yourwebsite.com/path/to/ssldir/$1 [R=301,L]

This rule will apply to every file in the same directory as the .htaccess file, and to all the files in its subdirectories as well.

Discussion

Many web surfers are familiar with the protocol acronym that signifies a secure web connection: the https:// that precedes the location of the page they're requesting. That doesn't mean, though, that they'll always use it, even when it's in their best interest to do so. You can help matters by carefully coding your links with the https:// prefix, especially when they target parts of your site where a secure connection is critical, such as your online store checkout or login form. But visitors who manually type in the address (or otherwise use http:// rather than https://) might be unnecessarily exposing their confidential information without knowing what they're doing.

The rewrite rule I've presented in the Solution tests the connection type and switches to a secure connection if the browser has not requested one.

Tip

As you've seen in other ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.