Thursday, May 2, 2013

Force a domain name to be served securely with htaccess

Add lines like these to your .htaccess file to force any http accesses to be rewritten using https:
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://yourdomain.com/$1 [R=permanent]
http accesses are served on port 80, and https accesses are served on port 443. The RewriteCond prevents the endless loop that would otherwise occur, by causing the RewriteRule to work only if the port is NOT 443. If this isn't working for you, first check your line endings. Copy/Pasting from your web browser into a text editor may not work right, so after pasting into your text editor you should delete each line break and add it back in (line break = return key). If it's still not working, change [R=permanent] to [R], some servers have a hard time parsing that argument.
Disqus Comments