Redirect Only Specific Files from HTTP to HTTPS

Jun 27, 2010 | Website Development

We had a hard time finding a solution to redirect only certain files from HTTP to the secure HTTPS. We found all kinds of ways to redirect the entire site to HTTPS but none for specific pages only. After a few hours tinkering, a solution using the following code in a .htaccess file was found:

Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^example.com [nc]
rewriterule ^(.*)$ http://www.example.com/$1 [r=301,nc]
 
rewritecond %{SERVER_PORT} !^443$
rewriterule ^filename.php(.*)$ https://www.example.com/filename.php$1 [r=301]

The first part of the code redirects example.com to www.example.com as noted in an earlier post, “301” Redirects for SEO. The second part then redirects a specific file (filename.php) from http to https. Thus the individual file “filename.php” can only be accesses using a SSL connection.