Important Must-Have .htaccess Snippets

Wordpress-code-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]

Replace example.com with the old domain name and example.net with the new domain name in this snippet.

By default the RewriteRule above removes the query strings (like ?product_type=dresses). The QSA flag helps you retain the query strings. So instead of [L,R=301,NC] you can use [QSA,L,R=301,NC].

5. Block visitors from a particular IP

order allow,deny
deny from 255.0.0.0
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
</IfModule>

7. Disabling access to a complete directory or website

# Apache 2.2
<IfModule !authz_core_module>
    Order Deny,Allow
    Deny from all
</IfModule>

# Apache 2.4+
<IfModule authz_core_module>
    Require all denied
</IfModule>

OR

# Apache 2.2
<IfVersion < 2.4>
    Order Deny,Allow
    Deny from all
</IfVersion>

# Apache 2.4+
<IfVersion >= 2.4>
    Require all denied
</IfVersion>
Divi WordPress Theme