Feb 05, 2018 in Snippets

A typical setup is one where you would redirect all non www and http requests to https://www.domainname.com. I prefer to keep my .htaccess file in version control also. With the following snippet, I get it the way I want it.

  # from non www to www, skip words live and staging in domain name, or extension .local
  RewriteCond %{HTTP_HOST} !^www\.
  RewriteCond %{HTTP_HOST} !\.local$ [NC]
  RewriteCond %{HTTP_HOST} !^(live|staging)- [NC]
  RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  # from http to https, skip words live and staging in domain name, or extension .local
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP_HOST} !\.local$ [NC]
  RewriteCond %{HTTP_HOST} !^(live|staging)- [NC]
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]