Useful .htaccess Snippets and Hacks

.htaccess is one file that every web admin should know and understand. At its basic level it controls access to your sites directories. But there is much more that you can do, as the snippets in this post will show you.

If you you would like to learn the basics of .htaccess, you should check our our Introduction to .htaccess article, which explains pretty well everything you will need to get you up and running.

So, here are some useful .htaccess snippets and hacks:

1. Controlling Access to Files and Directories

Password protection is one thing, but sometimes you may need to completely block users from having the option of accessing a particular file or directory. This usually happens with system folders, such as the includes folder for which applications will need access but no users will ever need the privilege.

To do this, paste this code onto an .htaccess file and and drop it in the directory:

deny from all

However, this will block access to everyone, including you. To grant yourself access you need to specify your IP address. Here is the code:

order deny,allow

deny from all

allow from xxx.xxx.xxx.xxx

xxx.xxx.xxx.xxx is your IP. If you replace the last three digits with 0/12 for example, this will specify a range of IPs within the same network, thus saving you the trouble to list all allowed IPs separately.

If you want to block access to a particular file, including .htaccess itself, use the following snippet instead:

<Files .htaccess>

order allow,deny

deny from all

</Files>

Similarly, if you want to allow given IPs, list them with allow from.

If you want to block access to particular file types, use this instead:

<FilesMatch ".(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">

Order Allow,Deny

Deny from all

</FilesMatch>

2. Disabling Directory Browsing

To prevent directory browsing, add this:

Options All -Indexes

However, if for some reason you want to enable directory browsing, change it to the following:

Options All +Indexes

3. Speeding-Up Load Times by Compressing Files

You can compress any type of file, not only images. For instance, to compress HTML files, use this:

AddOutputFilterByType DEFLATE text/html

To compress TEXT files, use this:

AddOutputFilterByType DEFLATE text/plain

You can also compress JavaScript, or add compression to multiple file types with one command:

AddOutputFilterByType DEFLATE application/javascript

AddOutputFilterByType DEFLATE application/rss+xml

Alternatively, if you want to compress all of your JavaScript, HTML, and CSS files with GZIP, you can use this:

<IfModule mod_gzip.c>

mod_gzip_on Yes

mod_gzip_dechunk Yes

mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$

mod_gzip_item_include handler ^cgi-script$

mod_gzip_item_include mime ^text\.*

mod_gzip_item_include mime ^application/x-javascript.*

mod_gzip_item_exclude mime ^image\.*

mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

</IfModule>

4. Protect Your Site against Hotlinking

If you don’t want your images hotlinked, add this to your .htaccess file:

RewriteEngine on

RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]

RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

Just replace yourdomain.com with your own and you are good to go.

5. Blocking Visitors Referred from a Particular Domain

If you have users from a particular domain you don’t welcome, you can ban them from your site. For instance, if your site gets listed in a place you don’t want traffic from (i.e. adult sites, blackhat sites, etc.), you can serve them with a 403 Forbidden page. You need to have mod_rewrite enabled but since it is usually on, you should be fine. Add this snippet:

<IfModule mod_rewrite.c>

RewriteEngine on

RewriteCond %{HTTP_REFERER} bannedurl1.com [NC,OR]

RewriteCond %{HTTP_REFERER} bannedurl2.com [NC,OR]

RewriteRule .* - [F]

</ifModule>

You need to replace bannedurl1.com and bannedurl2.com etc. with the domain names you want to blacklist. You may want to use the [NC] flag because it specifies that the domain name you’ve entered isn’t case sensitive. The [F] flag specifies the action to take – in this case to show the 403 Forbidden error. If you want to ban multiple sites, use the [NC,OR] flag for every domain but the last and if you want to ban a single domain use only the [NC] flag.

6. Blocking Requests from Particular User Agents

If your log files show particular user agents (bots or spiders) you can add a few lines to .htaccess and deny them access to your site:

RewriteEngine On  
RewriteBase /  
SetEnvIfNoCase Referer "^$" bad_user
SetEnvIfNoCase User-Agent "^badbot1" bad_user
SetEnvIfNoCase User-Agent "^badbot2" bad_user
SetEnvIfNoCase User-Agent "^badbot3" bad_user
Deny from env=bad_user

Replace badbot1, badbot1, etc. with the names of bots from your log files. This should keep such programs away from your site.

7. Caching Files

Another way to speed your site’s load times is via file caching. Here is what you need to add in order to cache files:

<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$">

Header set Cache-Control "max-age=2592000"

</FilesMatch>

You can add more file types (or remove some of them) to the sequence of files listed in this example – do what suits you. You can also use max-age to specify the amount of time in seconds that your files will live in the cache.

8. Disabling Caching for Particular File Types

If you don’t want to cache particular file types, it is easier not to include them in the cache sequence. However, sometimes files might get cached even if you you don’t explicitly list them there and in this case you may want to disable caching only for them. Most often you will want to disable caching for dynamic files, such as scripts. Here is how to do it:

<FilesMatch ".(pl|php|cgi|spl|scgi|fcgi)$">

Header unset Cache-Control

</FilesMatch>

Just pipe the files you want caching disabled for and this is it.

9. Bypassing the Download Dialogue

By default, when you try to download a file from a Web server, you get a dialogue that asks you if you want to save the file or open it. This dialogue is especially irritating with large media files or PDFs. If the files you have uploaded to your server are for downloads, you can save users the trouble and proceed straight to download. Here is what you need to set in .htaccess:

AddType application/octet-stream .pdf

AddType application/octet-stream .zip

AddType application/octet-stream .mp3

10. Renaming an .htaccess File

If for some reason, mostly security-related, you want to rename your .htaccess file, it is very easy to do it. In theory, renaming an .htaccess file shouldn’t cause problems with the applications running on your server but if by chance you notice such issues after you rename the file, just rename it back to its original name.

AccessFileName htac.cess

You also need to update any entries in the file itself or everywhere .htaccess is mentioned, otherwise you will be getting lots of errors.

11. Changing a Default Index Page

If you want your index page to be something different from the default index.html, index.php, index.htm, etc. this is very easy to do. Here is what you need to add to .htaccess:

DirectoryIndex mypage.html

Replace mypage.html with the actual URL of the page you want to use as index and you are done.

12. Redirecting to a Secure https Connection

If you are using https and you want to redirect users to the secure pages of your site, use this:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

13. Restricting File Upload Limits in PHP, Maximum Size of Post Data, Max Script Execution Time, etc.

.htaccess allows you to set some values that directly affect your PHP applications. For instance, if you want to impose upload limits in PHP, so that you don’t run out of hosting space because of large files, use this:

php_value upload_max_filesize 15M

Of course, you can set the value to anything you deem appropriate – 15M (MB) in this example isn’t fixed in stone. You can also restrict the maximum post size for uploading in PHP, To do it, add this:

php_value post_max_size 10M

Similarly, you can change 10M to any value that suits you. If you don’t want scripts to execute forever, you can limit their execution time with the help of the following:

php_value max_execution_time 240

240 is the number of seconds before the script will be terminated and as you guess, it could be any value. Finally, if you want to limit the time a script can parse input data, use this:

php_value max_input_time 180

And set any value in seconds that suits you.

14. Disguising File Types

Sometimes you wouldn’t like users, to know the file types of the files on your site. One way to hide this information is if you disguise them. For instance, you can make all your files look as if they are HTML or PHP files:

ForceType application/x-httpd-php
ForceType application/x-httpd-php

There is much more that can be done with .htaccess. For instance, you can set automatic translation of your site’s pages, or set the server timezone, or remove the www from URLs, or use fancy directory listings, etc. In any case, before you start experiments with .htaccess, always backup the original .htaccess, so if things don’t go as planned, you have a working copy to revert to.

Author: (26 Posts)

Ada is a fulltime freelancer and enjoys every second of it. She is also the Blogger Relations Manager at WinkPress.com, which is a web resource about leveraging WordPress, its themes, and plugins to create versatile and unusual websites.

Comments