circuit

.htaccess SSL redirect for single wordpress page.

I recently had a client site that necessitated a single page that would automatically redirect to a secure page for donations.

That meant, they’d be collecting credit card information as well as personal info and then passing it off to PayPal.

After setting up the secure certificates in the server and getting SSL working, the tricky part was getting the redirect to work.

Ideally, it would do this:

  • When a user accesses www.site.com/folder/SSLpage the server forces that page to go to HTTPS.
  • If any other page is accessed, it forces that page back to HTTP.

This was much trickier than it should have been, as none of the documentation I found on the web would do what I needed it to.

Here’s the resulting  code, with comments, that worked.

Please note: Make sure your apache configuration (httpd.conf) allows for overrides using .htaccess before proceeding.

In httpd.conf look for the line inside your <directory> statement that matches where your wordpress install lives:

[hr]

 

Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all


[hr]

Take note of the AllowOverride None statement, and change it to AllowOverride All.

Save the file and restart apache:

  • On RHEL/CentOS that’s #service httpd restart

Now, navigate to your WordPress root directory (sometimes /var/www/htdocs/wordpress or similar)

Use a text editor like nano or vi to create your .htaccess file, or edit the one that’s there.

Here’s what my working .htaccess looks like, with comments for ease of re-use:

[hr]


#Force secure Page/post

RewriteEngine on
#If current port is 80 (http)
RewriteCond %{SERVER_PORT} ^80$
#Then rewrite to HTTPS
#replace URI after the ^ with your wordpress permalink
RewriteCond %{REQUEST_URI} ^/page/name/here/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [L,S=1,R=301]


#Escape secure form page/post

#if current port is 443 (https)
RewriteCond %{SERVER_PORT} ^443$
#and you’re NOT on the page you specified above rewrite to http
#Replace URI after the ^ with the same permalink as above
RewriteCond %{REQUEST_URI} !^/page/name/here/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .? http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


#start wordpress

RewriteEngine On
#RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]


[hr]

If all goes well, the single page you specified in the permalink section above, will go to HTTPS and the rest will go to HTTP.

I’m open to discussion, as I’m sure there’s an Apache wizard out there somewhere who could improve on this code. But the amount of time I spent trying to get this to work compelled me to give it back to the community.