8 Great htaccess rules to improve your website
26 Comments
.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 </Files>
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> # 1 MONTH <FilesMatch "\.(jpg|jpeg|png|gif|swf|css|js)$"> Header set Cache-Control "max-age=2689743, public" </FilesMatch> # 2 DAYS <FilesMatch "\.(xml|txt|html|php)$"> Header set Cache-Control "max-age=172800, proxy-revalidate" </FilesMatch>
.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 </FilesMatch>
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.
Downloads
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!

Thx mate! this saved my ass ;)
Thanks a loooooooooooooooooooooot
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
Great Resource! Thanks.
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.
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.
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.
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.
I always spent my half an hour to read this blog’s articles or reviews every day along with a cup of coffee.
Thanks for sharing this great .htaccess tips.. I learnt a lot :)
Thanks for the share, 301 redirects have always baffled me
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.
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ę
amortyzatory
podwozia…
Podwozia…
- 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
natomiast
chwycił zbytnio skrzydła.
- Wagner… - sapn�.
Seriously this is a good webpage.
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
trzęsie.
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.
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.
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
Pretty! This has been a really wonderful article.
Thank you for supplying this info.
Also visit my website :: telecharger subway surfers
Совершенно верно! Идея отличная, согласен
с Вами.
Мой персональный блог … как заработать деньги
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.
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.
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.
Wow! After all I got a website from where I be able to really take
useful information concerning my study and knowledge.
26 Comments [ Leave a comment ]