17 Useful Htaccess Tricks and Tips

17 Useful Htaccess Tricks and Tips


17 Useful Htaccess Tricks and Tips

Introduction

Some people might not aware of the power of htaccess, I have 17 htaccess methods in this article which I have used or tested it before, and I think some of them are essential tricks and tips to protect your webserver against malicious attacks and other would able to perform simple tasks efficiently such as redirection and web server optimization.

Last but not least, if you have been looking for web hosting services, you might want to have a look at this unlimited web hosting. :)

General

The following htaccess will able to help you to achieve simple task such as redirection and web server optimization.

1. Set Timezone

Sometimes, when you using date or mktime function in php, it will show you a funny message regarding timezone. This is one of the way to solve it. Set timezone for your server. A list of supported timezone can be found here

SetEnv TZ Australia/Melbourne

2. SEO Friendly 301 Permanent Redirects

Why it's SEO friendly? Nowadays, some modern serach engine has the capability to detect 301 Permanent Redirects and update its existing record.

Redirect 301 http://www.queness.com/home http://www.queness.com/

3. Skip the download dialogue

Usually when you try to download something from a web server you get a request asking whether you want to save the file or open it. To avoid that you can use the below code on your .htaccess file

AddType application/octet-stream .pdf
AddType application/octet-stream .zip
AddType application/octet-stream .mov

4. Skip www

One of the SEO guideline is, make sure there is only one URL pointing to your website. Therefore, you will need this to redirect all www traffic to non-ww, or the other way around.

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

5. Custom Error page

Create a custom error page for each of the error codes.

ErrorDocument 401 /error/401.php
ErrorDocument 403 /error/403.php
ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php

6. Compress files

Optimize your website loading time by compressing files into smaller size.

# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

7. Cache files

File caching is another famous approach in optimizing website loading time

<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>

8. Disable caching for certain file type

Well, in the other hand, you can disable caching for certain file type.

# explicitly disable caching for scripts and other dynamic files
<FilesMatch ".(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>

Security

The following htaccess code will able to enhance the security level of your webserver. Hotlinking protection is pretty useful to avoid other people using images that stored in your server.

1. Hotlinking protection with .htaccess

Hate it when people stealing bandwidth from your website by using images that are hosted in your web server? Use this, you will able to prevent it from happening.

RewriteBase /
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?queness.com/.*$ [NC]
RewriteRule .(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]

2. Prevent hacks

If you want to increase the security level of your website, you can chuck these few lines of codes to prevent some common hacking techniques by detecting malicious URL patterns.

RewriteEngine On

# proc/self/environ? no way!
RewriteCond %{QUERY_STRING} proc/self/environ [OR]

# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]

# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR]

# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]

# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|[|\%[0-9A-Z]{0,2}) [OR]

# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|[|\%[0-9A-Z]{0,2})

# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]

3. Block access to your .htaccess file

The following code will prevent user to access your .htaccess file. Also, you can block multiple file type as well.

# secure htaccess file
<Files .htaccess>
order allow,deny
deny from all
</Files>

# prevent viewing of a specific file
<Files secretfile.jpg>
 order allow,deny
 deny from all
</Files>

# multiple file types
<FilesMatch ".(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

4. Rename htaccess files

You can also rename your .htaccess file name to something else to prevent access.

AccessFileName htacc.ess

5. Disable directory browsing

Avoid the server from displaying directory index, or the opposite.

# disable directory browsing
Options All -Indexes

# enable directory browsing
Options All +Indexes

6. Change default Index page

You can change the default page index.html, index.php or index.htm to something else.

DirectoryIndex business.html

7. Block unwanted visitor based on referring domain

 

# block visitors referred from indicated domains
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_REFERER} scumbag.com [NC,OR]
 RewriteCond %{HTTP_REFERER} wormhole.com [NC,OR]
 RewriteRule .* - [F]
 
</ifModule>

8. Blocking request based on User-Agent Header

This method could save your bandwidth quota by blocking certain bots or spiders from crawling your website.

# block visitors referred from indicated domains
<IfModule mod_rewrite.c>
SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT
SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT
Deny from env=HTTP_SAFE_BADBOT
</ifModule>

9. Secure directories by disabling execution of scripts

 

# secure directory by disabling script execution
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options -ExecCGI

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

47 comments

htacess noob Admin
Tue, 2nd November 2010
Bookmarked! Thanks for the tips! Reply
Craig
Wed, 3rd November 2010
Here's a better "remove www" technique:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
</IfModule> Reply
Paweł P.
Wed, 3rd November 2010
Gooood, saved!
Best regards! Reply
kevin Admin
Wed, 3rd November 2010
Craigs, Al Guevara: Thanks for the tips guys! Reply
QuasiPreneur
Wed, 3rd November 2010
Most awesomeness of lists.. I've read a lot of howto htaccess but this one takes the cake!! Well done!! Reply
Morgan Capron
Wed, 3rd November 2010
Thanks, very useful post.
Reply
Al Guevara
Wed, 3rd November 2010
# 2 is incorrect

BAD:
Redirect 301 http://queness.com/home http://queness.com/home


GOOD:

Redirect 301 /home http://queness.com/home Reply
Andy
Wed, 3rd November 2010
Very good article, re-tweeting it as @andymalaga Reply
Marshall
Wed, 3rd November 2010
This is wonderful!
I am going to try that all today :)
Disabling Directory Browsing is the most important one for me I think.. Reply
m
Wed, 3rd November 2010
3. Block access to your .htaccess file
It's blocked by default, no need for this Reply
du hoc uc
Wed, 3rd November 2010
This post is high quality in usage.I need its,Thanks so much Reply
kevin Admin
Thu, 4th November 2010
ceasar, try this one:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] Reply
Alex K
Thu, 4th November 2010
Nice one! I've been looking for these snippets all over the place!
Thanks
abiteof.com Reply
ceasar
Thu, 4th November 2010
Graig wrote
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
</IfModule>

But how the other way. So everything with www.

Thanks Reply
wer
Sat, 6th November 2010
Don't use this hack for skipping download dialogue.

Use Content-Disposition:attachment instead (filename attribute is not needed BTW!)
Reply
Morten Fangel
Sun, 7th November 2010
Security #4 is pointless, and security-by-obscurity. Also, when you have #3 to prevent access in the first place, why bother

Security #3 is equally pointless, as the default config that apache ships with is set to deny access to any files starting with ".ht" (ie .htaccess and .htpassword)

Security #9 is quite poor at disabling execution of php scripts, as php is usually dealt with by a module, not cgi. (it is however some times, so can technically be useful).
To disable php scripts execution when using mod_php, you need to change the mime-type for .php

Lastly, security #6 has nothing to do with security, really... Reply
anehra63
Tue, 9th November 2010
a very good article. Reply
C.F. Action
Wed, 10th November 2010
Nice read... Some useful stuff here and some not so useful...

But great info = Thank You!

Cheers!~ Reply
anehra63
Wed, 10th November 2010
Cool stuff bro keep them coming Reply
Jonathan Dingman
Thu, 11th November 2010
With the case for #4, renaming the htaccess file, do you need to have an .htaccess file AND the new file so the webserver knows how to read where the new file is? Reply
amarnath
Thu, 11th November 2010
This is the first time am learning about .htaccess.
Thanks! Reply
Mem
Fri, 12th November 2010
Really nice - Thanks Reply
Edwin
Fri, 12th November 2010
Good htaccess directives recopilation : ) Reply
marlaw
Fri, 12th November 2010
nice article. Thanks for the info., and keep them coming. Reply
Bjorn Roesbeke
Fri, 12th November 2010
Security #2:
Why would one do that? Just don't echo unvalidated arguments.

Disable the php flag register_globals if it isn't already. Reply
Advitum Webdesign
Sun, 14th November 2010
Hey, this is great, especially the www-stuff!

Thanks! Reply
thedude
Thu, 25th November 2010
Nice, will definitely be using this as a reference. Thanks! Reply
masterb
Thu, 9th December 2010
Great articles, tested all examples, all work perfectly. Thanks Reply
Brown Joe
Wed, 16th March 2011
How would you deny all visitors to one file, but allow a few IP to view it??
Is that even possible?? Reply
MickeyRoush
Tue, 29th November 2011
Order Allow,Deny
<FilesMatch "^file.php$">
Allow from 123.456.789.123
Allow from 456.789.123.456
</FilesMatch> Reply
Mr asif Khaan
Mon, 28th November 2011
Thanks..Great Really you saved us... i appreciate you Reply
suzi
Sun, 8th January 2012
Hi, I am new to html and hpaccess, but have a wordpress website and I am trying to do
#3 AddType application/octet-stream .pdf
I am not sure where to insert this. Can someone guide be from the WP htaccess control page?
Would really appreciate some help,
Thanks, S Reply
Doug Wilson
Wed, 16th May 2012
I'm trying to deal with scrapers and a certain file type (.pdf)

I was hoping for an overall bot directive "don't crawl file type"

So far, no dice Reply
LevineDoreen
Sat, 29th December 2012
It is understandable that cash makes us independent. But what to do if somebody does not have cash? The only one way is to receive the <a href="http://goodfinance-blog.com ">loans</a> and financial loan. Reply
chris
Mon, 28th January 2013
timezone code worked perfect! thank you
Reply
FranciscoNET
Mon, 18th February 2013
Hi,
I am having problems with:
# prevent viewing of a specific file
<Files secretfile.jpg>
order allow,deny
deny from all
</Files>

I am trying to deny the file: postback.php except for 4 IP address that they are allowed, the first 3 of them is 72.52.162.102
199.59.164.3
199.59.164.5

and the 4th one is my own ISP IP address. I have tried many ways, but it fails. What would the correct syntax be?

Thanks Reply
Nick
Sat, 2nd March 2013
Most of my htaccess codes come from here. thanks a lot! Reply
Sandeep
Wed, 27th March 2013
Awesome. I searching for this. Reply
chaim
Sat, 27th April 2013
Very useful document
Thanks Reply
cto.vn
Tue, 11th June 2013
Thanks for this post... i linke this post Reply
Jennifer Hardy
Fri, 2nd August 2013
The best tips i have seen, good work........ Reply
Tomb
Sun, 4th August 2013
Awesome ! post ... I love it ..... Thanks a lot !!!! :-) Reply
Ege
Mon, 23rd September 2013
thanx man Reply
Chris
Sun, 13th October 2013
Great article!

Two questions:
1) I'm blocking some IP addresses that site hacks originated at - can I also block the redirect url's that were pointed to by the hack in the same rule set? here is what I have:
---------------snip-----------------------

# Block IP addresses & URL's
order allow,deny
deny from 95.168.173.88
deny from daranya.com
deny from naspletu.org
deny from mount4him.org
deny from fecatt.org
allow from all

-------------------------snip--------------
or, do I have to block the junk url's in a different way?

2) From your item #7

# block visitors referred from indicated domains
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} scumbag.com [NC,OR]
RewriteCond %{HTTP_REFERER} wormhole.com [NC,OR]
RewriteRule .* - [F]
</ifModule>

............
do I need to include the [NC,OR] - and if so, what does this represent?

Thanks so much for your help!
:) Reply
world
Sun, 24th November 2013
Hello. I am forced to change the range each week., Please give me a code for htaccess Reply
Felipe
Wed, 28th May 2014
Great!! Thanks man!! Reply
CouponMeUp
Fri, 8th August 2014
This really helped me! Just working on our site and this really saved me some time!
Our servers output javascript as text, so if yours does, add this:
AddOutputFilterByType DEFLATE text/javascript
Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement