.htaccess rules for every site

I recommend that you start off with a good boilerplate htaccess file for your websites. This file should be named .htaccess and it should be located at the root of your website. I use the following boilerplate when I start a new site.

If you just want a couple of rules that really are must haves. All of these should be covered in the boilerplate above. In many of the rules, you will need to make sure that you customize them with your domain name.

Disable Directory Listing

Everyone should have this unless you have a very good reason.

Options -Indexes

Force SSL

Nowadays, every website should have an SSL certificate so that the website can be served over HTTPS. Your hosting company wants to charge you for an SSL certificate, it's time to find a new hosting company. But that is a different topic. The following rule will redirect all requests to use SSL. Every website should have this. EVERY WEBSITE.

RewriteEngine On 
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

Force www vs Remove www

This is a personal preference but you need to choose one or the other. either your website will always have www or it never should.

Remove www:

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

Force www:

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

404 Pages

My SEO Helper stacks can help you with this. But here is a rule that you can add to point to your 404 page that you should build in your project.

ErrorDocument 404 http://example.com/path/to/page.html

HTML vs PHP default page URL

By default web servers will always serve an index.html file over an index.php file in the case both exist. Since I almost always prefer to use PHP, I prefer to change the order. We can do that with the following rule.

Note: You never really want to have both in there. You should delete one. However, this rule, makes things better for my workflow until I can fix the issue manually.

DirectoryIndex index.php index.html

Block iFrames

It's probably a good idea to block other people from adding your website into an iframe from a different domain. The following configuration will block others from embedding your webpages into an iframe on their websites. But it will allow you to still embed your webpages into an iframe on the same domain.

Header always set X-FRAME-OPTIONS "SAMEORIGIN"

There are other values available for this. You see the docs for X-Frame-Options for more details.

17
8 replies