In the past I merely lifted htaccess code from online but never really understood how parts of it worked. So, I attempted to add some documentation around 3 common scenarios 1) forcing “www” version of your website 2) enabling web-friendly URLs and 3) forcing specific pages to be HTTPS (this works in localhost vhost setup with self-signed cert).
Let me know your thoughts, suggestions, or if I completely missed the mark with anything. Feel free to add as well.
RewriteEngine on
Options +FollowSymLinks
#force redirect to "www" version of the URL
#also appends REQUEST_URI (i.e, $1) to redirected version of URL
#tell browser or agent this is a permanent redirect
RewriteCond %{HTTP_HOST} ^domain1\.com
RewriteRule ^(.*)$ <a href="http://www.domain1.com/$1">http://www.domain1.com/$1</a> [R=permanent,L]
#rewrite friendly URL and pass to CI web app in proper format (i.e, which includes "index.php")
#ignore requests made directly to index.php, robots.txt, favicon.ico
#or files in folders images, assets and js
#example rewrite: <a href="http://www.domain1.com/web/about">http://www.domain1.com/web/about</a> => <a href="http://www.domain1.com/index.php/web/about">http://www.domain1.com/index.php/web/about</a>
RewriteCond $1 !^(index\.php|images|assets|js|robots\.txt|favicon\.ico)
RewriteRule ^(.*)$ /index.php/$1 [L]
#GOAL: force https for login page
#IF request on port 80 and not made directly to index.php, robots.txt, favicon.ico
#or files in folders images, assets and js
#THEN create a rewrite rule for URI /user/login to redirect ("Found 302") to https
#version of URL. "$1" backreferences "(.*)", which is anything appended after
#after "/user/login". "$1" appends additional data to the secured version of the URL
RewriteCond %{SERVER_PORT} 80
RewriteCond $1 !^(index\.php|images|assets|js|robots\.txt|favicon\.ico)
RewriteRule /user/login(.*)$ https://%{HTTP_HOST}/user/login$1 [L]
#force https for registration page
RewriteCond %{SERVER_PORT} 80
RewriteCond $1 !^(index\.php|images|assets|js|robots\.txt|favicon\.ico)
RewriteRule /user/register(.*)$ https://%{HTTP_HOST}/user/register$1 [L]