Apache: Forcing SSL using mod_rewrite and .htaccess

If you want to force all connections to your Apache web server to use SSL (https), you can do so with a simple .htaccess file inside the directory you want to protect:
# Force SSL connections
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

Make sure you get all the proper spacing in there, or else it won’t work! I spent quite a bit of time pulling my hair out trying to get this to work, only to find out I was missing a space somewhere.