5 Must-Have .htaccess Snippets


1. Redirecting HTTP to HTTPS

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

2. Redirecting www to non-www

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

3. Redirecting non-www to www

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

4. Redirect Old Domain To New Domain

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

5. Block visitors from a particular IP

order allow,deny
deny from
deny from 123.45.6.
allow from all

There are a few more snippets that I tend to use and as time passes I wish to keep this page updated for my own handy info.

6. Simple 301 redirect

<ifmodule mod_rewrite.c>
RewriteEngine On
Redirect 301 /some-url-without-domain-name https://www.example.com/url-to-be-redirected-to
Posted In:

Support & Maintenance, Code Snippets

Comment on 5 Must-Have .htaccess Snippets

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