8 Great htaccess rules to improve your website

32 CommentsOn: 8 Great htaccess rules to improve your website

htaccess rules

.htaccess files are incredibly useful and versatile – it allows us to do the following all from a single simple file that resides in the root directory of your website server.

You should be fairly skilled with Web development before meddeling with or creating .htaccess rules.

Benefits of using .htaccess rules

  • Enforcing or removing the www prefix in URLS
  • Prevent directory listings and viewing of .htaccess file
  • Handling custom 404 (File not found) error pages
  • Using cache control to improve Website performance
  • .htaccess can force download prompts for certain file types
  • Redirect from olddomain.com to newdomain.com
  • .htaccess temporary page re-direct during maintenance
  • SEO friendly .htaccess rules for single pages redirects

Does my host support .htaccess rules?

As a general rule, if your server runs Unix or Linux, or any version of the Apache web server it will support .htaccess rules, although your host may not allow you to use it.

What we are going to do

I will just be giving code examples and downloads that can be copied, pasted and tweaked to suit your needs as creating .htaccess files can be complicated.

.htaccess files can be edited in notepad or any basic text or developer program such as Dreamweaver, avoid Microsoft Word as it may save or input unwanted characters.

Backup your existing .htaccess file on your server before making changes, and note, changes made in your .htaccess file can stop your site from working properly or even totally, if it does – reverse your changes by restoring the backup file, or deleting the one you uploaded – problem solved!

Download one of the .htaccess files at the end of this article to re-use or tweak to suite your needs.

.htaccess rules to enforce or remove www prefix in URLS

First off, we comment code in a .htaccess file by starting a line with # the remainder of that line will not be processed, now lets wade into the code!

# Redirect all users to access the site WITHOUT the www. prefix
RewriteEngine on
rewritecond %{http_host} ^www.pgwebdesign.net [nc]
rewriterule ^(.*)$ http://pgwebdesign.net/$1 [r=301,nc]

This .htaccess rule re-writes all urls/pages accessed on this domain without the www prefix, 301 means permanent – if we used 307 it would be temporary, type in your address bar www.pgwebdesign.net and see it re-write it without the www.

As you can see I use this on my website, it keeps the URLS shorter and prevents duplicate content, while I link to all my urls without the www prefix, other website that link to me may use www, and by default the same page can be accessed with or without the prefix, for example http://example.com/hi/ and http://www.example.com/hi/ are pointing to the same page, but are considered separate by search engines, we want to prevent this.

You may also enforce using the www prefix (below), either rule has the same end result, it’s down to preference, if your unsure enforcing www can be the safer bet. Remember to change the domain name to your own.

# Redirect all users to access the site WITH the www. prefix
RewriteEngine on
rewritecond %{http_host} ^domain.com [NC]
rewriterule ^(.*)$ http://www.domain.com/$1 [R=301,nc]

Prevent directory listings and viewing of .htaccess file

To prevent users from poking around or reading our .htaccess rules, add the following into the .htaccess file.

# Disable directory listing from this point
Options -Indexes

# Prevent viewing of htaccess file
<Files ~ "^\.ht">
order allow,deny
deny from all
satisfy all

Custom 404 (File not found) error pages

All websites or at the very least all medium-large websites should have a 404 page, the last thing a user needs to see when they land up on a page that has moved, no longer exists or is typed wrong is something like this:


Here are some resources for creating a usable and friendly 404 error page:

The Perfect 404 by A List Apart

50 Creative and Inspiring 404 Pages by Webdesigner Depot

After you have created a custom 404 error page, we can tell our server to fetch our custom 404 file instead of spewing out the default error.

In this case our 404 file is called 404-error.html and we have placed it in the root folder, usually public_html or www in our ftp directory.

# Error Pages
ErrorDocument 404 /404-error.html

.htaccess rules for cache control / performance

If you have a Website with pages or file types that aren’t updated too often we can cache these resources, saving bandwidth and improving the speed at which content is delivered to the user.

Below is just an example, adjust file types accordingly, the “max-age=” is the amount of seconds if you wish to alter it.

# Cache Certain file types, saving bandwidth and decreasing load times

# 1 YEAR
<FilesMatch "\.(ico|pdf)$">
Header set Cache-Control "max-age=29030400, public"

<FilesMatch "\.(jpg|jpeg|png|gif|swf|css|js)$">
Header set Cache-Control "max-age=2689743, public"

# 2 DAYS
<FilesMatch "\.(xml|txt|html|php)$">
Header set Cache-Control "max-age=172800, proxy-revalidate"

.htaccess rule for forcing download prompts for certain file types, like forcing PDF’s to download and not open

Don’t you hate it when you click on a pdf link and it tries and sometimes fails to open in the browser? using this rule we can force it to prompt us to download the file.

# Force all PDF files to download
# Requires Apache Header Module - this will work for any file extensions

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment

Redirect from olddomain.com to newdomain.com

Let’s say you have an old website that is accessible under olddomain.com and you have a new website that is accessible under newdomain.com. Copying the content of the old website to the new website is the first step, then
you should do a 301 moved permanently redirect from the old domain to the new domain, or a 307 if it’s temporary.

The advantages of doing this are:

  • Users will automatically be redirected to the new domain
  • Search engines will be redirected to the new domain
  • Google’s PageRankTM will be transferred to the new domain, in addition to internal information that is being used to set the position of pages in the search engine result pages (serp’s)

The Solution? – a 301 (permanent) redirect for all http requests that are going to the old domain, change newdomain.com to the relevant domains name, and place this file on your old domain.

# 301 Redirect of all http requests to a new domain
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !newdomain.com$ [NC]
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [L,R=301] 

Re-direct users to a temporary page during maintenance

Need to update some content that might disrupt users currently browsing the website? or you might have been hacked :( for this we redirect all users to a temporary page while maintenance is being performed, in this case I have made a file called maintenance.html and uploaded it to our root directory, whenever maintenance needs to be performed, add this rule to your .htaccess file and all users who access your website will be temporary re-directed to the maintenance page, this method is also SEO friendly.

# Temporary maintenance page redirect
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteRule .* /maintenance.html [R=307,L]

SEO friendly redirects for single pages

Let’s say you have a page called http://mywebsite.com/na89s3.html, which you want to rename, but you don’t want to change it because users won’t be able to find it and all the search engines are pointing to it, no problem! we can do a permanent (301) or temporary (307) redirect, which automatically points users to the new page. (The new page still needs to exist at the new destination.)

# 301, Permanent single page redirects
redirect 301 /oldname.html http://www.domain.com/new-useful-name.html
redirect 301 /blog/example.html http://www.domain.com/blog/new-name.html

You can make sure you did this correctly by going to the old page name and looking at the address bar to see if it changes to point to the new address.


Blank htaccess templateExample htaccess file

Feeling Brave?

If you looking for something really in-depth with a ton of complex .htaccess rules and relish a challenge then, the Ultimate Htaccess Documentation is for you.

Things To Remember

  • The .htaccess file is used primarily on Unix/Linux based servers and requires Apache, if you are unsure contact the company hosting your website.
  • .htaccess is the file extension. It is not file.htaccess or somepage.htaccess, it is simply called .htaccess
  • RewriteEngine On does not need to be written more than once in an .htaccess file, once it’s on it’s on.
  • While your server/host may support .htaccess rules, they may not support each of these rules as they may require a module your host does not have.

If you have any other cool use’s for .htaccess files, why not leave a comment?

Share or Save!

July 4, 2010 at 9:49 am #1

Thx mate! this saved my ass ;)

July 4, 2010 at 1:10 pm #2

No problem, glad you found it useful :)

March 24, 2011 at 3:26 pm #3

Thanks, great article.

James R
December 23, 2011 at 10:10 pm #4

Thanks, Good wright up.

August 8, 2012 at 7:03 am #5

Thanks a loooooooooooooooooooooot

Suneel Kumar
September 6, 2012 at 11:58 am #6

Thanks for the posting. It would be helpful if you can add how to hide the static page direct access without logging into the portal

January 10, 2013 at 2:11 am #7

Great Resource! Thanks.

web design companies in singapore,web design,singapore web design company
January 19, 2013 at 9:10 pm #8

Heya i am for the primary time here. I found this board and I to find It really useful & it helped me out a lot. I hope to give something again and help others such as you helped me.

furniture website templates
April 30, 2013 at 1:21 am #9

A number of people in no way go on to the level you
possess in the works. Your site 8 Great htaccess rules to
improve your website support me within obtaining some necessary details.

Should you keep this way up creating I do think you
may be an energy in this particular market.

May 22, 2013 at 1:06 pm #10

It’s actually a nice and helpful piece of info. I am satisfied that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.

外汇foreign exchange
June 8, 2013 at 3:00 am #11

of course such as your web-site nevertheless, you must analyze this transliteration on several of one’s discussions. Some of them are usually filled along with transliteration challenges and I locating the item incredibly disturbing to tell the fact then again I am going to unquestionably are available just as before all over again.

July 20, 2013 at 7:38 am #12

I always spent my half an hour to read this blog’s articles or reviews every day along with a cup of coffee.

Karthikeyan K
July 29, 2013 at 10:37 am #13

Thanks for sharing this great .htaccess tips.. I learnt a lot :)

August 12, 2013 at 5:55 pm #14

Thanks for the share, 301 redirects have always baffled me

November 19, 2013 at 7:32 pm #15

Your blog seems to be having some compatibilty issues in my opera browser. The text appears to be running off the webpage pretty bad. If you would like you can e-mail me at: and I will shoot you over a screen shot of the problem.

November 27, 2013 at 2:13 pm #16

wzniesionego pyłu, Pokojowa maszyny. kiedy oprowadzacz pociągnął

dźwignię modyfikacji skoku, Podnosniki24.biz[http://www.myunfinishedbusiness.com/index.php/member/99530] podczas gdy drgnął korpus oraz wydłużyły się



- Wagner! – Frodo obrócił się raptownie, nie zawracając samemu łba ocieraniem

łez ściekających po policzkach.

Wagner stuknął szpadlem w chodnikowe niedbały, podczas gdy Frodo podskoczył do niego

chwycił zbytnio skrzydła.

- Wagner… – sapn�.

Recommended Reading
December 6, 2013 at 10:19 pm #17

Seriously this is a good webpage.

ciepło czy zimno
January 14, 2014 at 6:14 pm #18

zie, w ogonie W tym momencie będziesz uzyskała szyki w własnej trwałości, przebija, natomiast w obrębie ciepło czy zimno


Podejrzenie, że Frodo boi się koni, stało niesłuszne.
Standardowo się wstydził,

bo z racji swej postury również wzrostu wypatrywał na koniu nieco śmiesznie.

Jak indywidualnym źródłem umeblowania w ropę pozostały
norweskie pola naftowe,

ogół, jaki mógł, kombinował jedną chabetę, Norwegowie postanowili zbyć,
jak bardzo

się zainstaluje, Na Bl.

mario mobile games
April 15, 2014 at 3:42 pm #19

I love what you guys tend to be up too. This kind of clever work and exposure!
Keep up the good works guys I’ve incorporated you guys to our blogroll.

telecharger teamviewer
April 21, 2014 at 12:09 pm #20

Hi there to every one, the contents present at this web page are actually amazing for people knowledge, well, keep up the good work fellows.

my web-site: telecharger teamviewer

telecharger subway surfers
April 21, 2014 at 12:44 pm #21

Pretty! This has been a really wonderful article.
Thank you for supplying this info.

Also visit my website :: telecharger subway surfers

как заработать деньги
May 27, 2014 at 8:45 am #22

Совершенно верно! Идея отличная, согласен
с Вами.

Мой персональный блог … как заработать деньги

Karl V. Ruh
October 9, 2014 at 5:28 pm #23

If some one needs to be updated with newest technologies then he must
be go to see this site and be up to date everyday.

candy sugar skull
October 21, 2014 at 6:10 am #24

My spouse and I stumbled over here different page and thought I might check things out.
I like what I see so now i am following you. Look forward to finding out about your web page again.

online games
February 2, 2015 at 1:47 pm #25

I have been exploring for a little bit for any high-quality articles or blog posts on this sort
of space . Exploring in Yahoo I ultimately stumbled upon this web site.
Studying this info So i am glad to show that I’ve
an incredibly excellent uncanny feeling I came upon just what I needed.
I most unquestionably will make certain to do not disregard this web site and
provides it a glance regularly.

Sony Vegas Pro
February 25, 2015 at 3:38 am #26

Wow! After all I got a website from where I be able to really take
useful information concerning my study and knowledge.

download teamviewer free software 4ustudy
May 13, 2016 at 2:48 am #27

Wonderful web site download teamviewer free software 4ustudy. Many useful info in this article. I’m giving them to a few associates ans furthermore sharing in delectable. Not to mention, appreciate your effort!

October 14, 2016 at 6:40 pm #28

I do not know if it’s just me or if perhaps everyone else experiencing problems with your site.
It appears as though some of the written text within your content are running off the screen. Can someone else please comment and let
me know if this is happening to them too? This may be a problem with
my web browser because I’ve had this happen before.
Appreciate it

Snack Subscription
October 12, 2018 at 3:02 pm #29

Appreciating the time and energy you put into your site and detailed information you provide.

It’s great to come across a blog every once in a while that isn’t the
same unwanted rehashed material. Excellent read! I’ve bookmarked your site and I’m
adding your RSS feeds to my Google account.

czy można założyć konto bankowe przez internet
October 24, 2018 at 4:20 pm #30

A fascinating discussion is definitely worth comment. I do think that you ought to publish more on this issue, it might
not be a taboo matter but generally people do not talk about such subjects.
To the next! Cheers!!

October 24, 2018 at 9:22 pm #31

Excellent factors totally, you only been given a completely new target audience. Quantity you highly recommend relating to aplikasi berita saham terbaru your posting for you to created few days during the past? Any certain?

December 3, 2018 at 10:01 pm #32

I do not even know the way I ended up right
here, however I thought this put up was great. I don’t recognize who you’re but definitely you are going to a
famous blogger if you aren’t already. Cheers!

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>