Top htaccess rules for web developers

In this blog post I am going to share some of the top htaccess rules for web developers that are regularly required almost in every application. Through htaccess developers can override apache settings and depends on configuration of web server. Often during web development you might require certain htaccess rules to handle certain tasks like rewriting, redirection, handling cors etc.

TOP HTACCESS RULES:

RULE 1: Redirect non-www urls to www

Option 1: It will 301 redirect non-www urls to www.


RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.exampledomain\.com
RewriteRule (.*) http://www.exampledomain.com/$1 [R=301,L]

Options 2: This will work same as option 1


RewriteEngine on
RewriteCond %{HTTP_HOST} ^exampledomain.com$ [NC]
RewriteRule (.*) http://www.exampledomain.com/$1 [R=301,L]

Option 3: Same as above


RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RULE 2: Redirect www urls to non-www

Option 1: It will 301 redirect www urls to non-www.


RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.exampledomain\.com
RewriteRule (.*) http://.exampledomain.com/$1 [R=301,L]

Options 2: This will work same as option 1


RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.exampledomain.com$ [NC]
RewriteRule (.*) http://exampledomain.com/$1 [R=301,L]

RULE 3: Redirect http to https

Option 1: It will 301 redirect http urls to https.


RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Option 2: Same as above.


RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *