Apache htaccess

Apache htaccess

Web Stuff 25.08.2015 3821


Apache htaccess

A few redirects for your root directory if your server is running on apache.

Your .htaccess file should start with following two lines:

RewriteEngine on
RewriteOptions MaxRedirects=1

Now we have different rules depend what you like to achieve.

Force www
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]
Force non-www
RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]
Force https
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
Force https and www
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
Force https and non-www
RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
Force https and www for main domain only
RewriteCond %{HTTP_HOST} ^domain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.domain.com$
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]

If you have any suggestion or questions feel free to post a comment.