How to Get The Most Out of Your .htaccess File

If you’ve been a web designer for any length of time, chances are you’ve run across the mysterious “.htacess” file at one point or another. Others may ask, what’s an “ht” and why do I need access to it? Whether a beginner or pro, though, knowing what the htaccess file does and can do for you, can enhance a site’s performance, security and more.

How to Get The Most Out of Your .htaccess File

Standing for “hypertext access,” the htaccess file is simply a configuration file sitting on the directory level of your website that lets you manage the server’s configuration. In WordPress installations, one of the file’s key jobs is simply to tell the server to recognize and run WordPress. But here’s what else this nifty little jumble of code can do for you. And beginner or pro, ALWAYS backup the file before you proceed.

1. Prohibit directory browsing

While being able to browse directories can be useful, leaving them open for everyone to browse poses some pretty big security risks. Stopping directory browsing is as simple as adding the following to your htaccess file somewhere between “# BEGIN WordPress” and “# END“:

Options All -Indexes

2. Stop Hotlinking

Text pirates who copy your website’s content are bad enough for all sorts of reasons, but image hijackers are equally bad although they don’t actually steal your graphic content, but borrow it by linking to and loading images from your site. Again, it’s a practice that gives rise to a number of security concerns and uses up your bandwidth, too. Prevent it by adding the following to your htaccess file, replacing “mywebsite.com” with your own.

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

3. Display a custom error page

There are all sorts of reasons for displaying custom error pages. While many WordPress themes let you easily set custom pages, you can also quickly do it in your htaccess file by adding one or more of the following:

ErrorDocument 404 /404.html
ErrorDocument 403 /403.html
ErrorDocument 500 /500.html

Of course, you’ll also need to create and load the custom pages as well.

4. SEO optimized 301 permanent redirects

Anytime you change the URL structure of website during a redesign or server migration, you may need to redirect old pages. Just add the following with the old address followed by the new address to preserve a page’s SEO rank.

Redirect 301 http://www.mysite.com/article.html http://www.mysite.com/archives/article

5. Block unwanted visitors from referring domain

While no webmaster usually wants to block traffic to a site, there are times when it’s necessary. The following added to the htaccess file will block traffic from a specific domain.

RewriteEngineon
RewriteCond %{HTTP_REFERER} wearespammers.com [NC]
RewriteCond %{HTTP_REFERER} subdomain.wearespammers.com [NC]
RewriteCond %{HTTP_REFERER} baddomain. [NC]
RewriteRule .* - [F]

The first line checks if the referrer is wearespammers.com, the second for subdomains, and the third for any domain extensions such as .org, .net., etc.

6. Block visitors from specified IP addresses

You can also block specific IP addresses or blocks of addresses. The following, for instance, blocks traffic from 145.177.12.119 and subdomains of the IP block 012.43.4.

allow from all
deny from 145.177.12.119
deny from 012.43.4.

7.Allow accessonly from certain IP addresses

Use the following to allow visitors from specific IPs or a range.

orderdeny,allow
deny from all
allow from 128.338.488.011
allow from 496.742.011

This code denies access to everyone except users with an IP address of 123.456.789.012 or in the range 496.742.011.xxx.

8. Changing a directory’s default page

Need something other than index.php or index.html to be the default page of your website? Then add this line to your htaccess file

Directory Indexnewpage.html

9. Specify upload limit for PHP

If you’ve ever run into issues with large files being uploaded to your site, use the htaccess file to set parameters. The first value in the following refers to the maximum file size that can be uploaded, the second the maximum size of post data, the third the maximum number of seconds a script can run before being terminated, and the last the maximum time a script can parse input data.

php_value upload_max_filesize 30M
php_value post_max_size 30M
php_value max_execution_time 400
php_value max_input_time 400

10. Force file caching

Speed up your website for repeat visits by telling visitors’ browsers that content won’t change for a set period of time. The following sets three different time spans for different type files (all times in seconds).

# 1 year
<filesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=31536000, public"
</filesMatch>
# 2 days
<filesMatch ".(xml|txt)$">
Header set Cache-Control "max-age=172800, public, must-revalidate"
</filesMatch>
# 2 hours
<filesMatch ".(html|htm)$">
Header set Cache-Control "max-age=7200, must-revalidate"
</filesMatch>

Note that the revalidation prompt forces browsers to check for changes after the initial period.

11. Add a trailing slash

Some experts say a trailing slash helps SEO while others say it doesn’t. But since it doesn’t hurt:

<IfModulemod_rewrite.c>
RewriteCond %{REQUEST_URI} /+[^\.]+$ 
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</IfModule>

12. Add expires headers

Like forced caching, expires headers tell browsers files won’t change for a certain time, meaning those browsers don’t have to reload them each time.

<ifModulemod_expires.c>
ExpiresActiveOn
ExpiresByType text/html "access plus 2 days" 
ExpiresByType image/gif "access plus 60 days"
ExpiresByType image/jpg "access plus 60 days"
ExpiresByType image/png "access plus 60 days" 
ExpiresByType application/x-javascript "access plus 60 days"
ExpiresByType text/css "access plus 60 days"
ExpiresByType image/x-icon "access plus 360 days"
</IfModule>

While the default time is specified in seconds, you can also use minutes, hours, days, weeks, months and years.

13.Password protect directories

You’ll need to first create a text file called “.htpasswd” and place it above your root directory so it won’t be accessible at http://mydomainname.com/.htpassword. In this file you’ll add password information for your site with the username followed by the password:

username1:password1
username2:password2

Next create a new “.htaccess” file and upload it to the directory you want to protect with the following:

AuthUserFile /path/to/htpasswd/file/.htpasswd
AuthGroupFile /dev/null
AuthName "name of directory"
AuthType Basic
require valid-user

The first line is the full server path to your htpasswd file. If you want a specific user only to have access, you would replace the last line with:

require user username1

14. Password protect individual files

To block an individual file, you’ll need to create or add to your existing htpasswd file and create and upload an htaccess file to the directory in which the file you want to protect resides:

AuthUserFile /path/to/htpasswd/file/.htpasswd
AuthName "Name of Page"
AuthType Basic
<Files "thepage.html">
require valid-user
</Files>

15. Protect htaccess files

For an added layer of security, protect your htaccess file with the following:

<Files .htaccess>
Order Allow,Deny
Deny from all
</Files>

A 403 error file will be displayed. The file name can be changed to whatever file you wish to protect as long as it is in the same directory as a specific htaccess file.

16. Disable display of download request

If you don’t want visitors to have the option of viewing or downloading certain file types, add the following so files automatically download:

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

17. Compress with mod_deflate

Speed up downloads and loading times for visitors with Apache mod_deflate module that compresses output by as much as 70%.

<ifmodulemod_deflate.c="">
<filesmatch ".(js|css|.jpg|.gif|.png|.tiff|.ico)$"="">
SetOutputFilter DEFLATE
</filesmatch>
</ifmodule>

18. Remove category from a URL

Want to shorten a url like http://yourdomain.com/category/apples to just http://yourdomain.com/apples? Add the following:

RewriteRule ^category/(.+)$ http://www.yourdomain.com/$1 [R=301,L]

19. Google Text Translation

Need certain pages on your site to translate to another language? The following redirects pages ending in “.fr,” “.de,” etc., to the Google translation for that language.

Options +FollowSymlinks
RewriteEngineOn
RewriteBase /
RewriteRule ^(.*)-(fr|de|es|it|pt)$ http://www.google.com/translate_c?hl=$2&sl=en&u=http://site.com/$1 [R,NC]

20. Use a different file extension

Want to change your file extensions from .php to .wow or anything else for that matter? Add:

Options +FollowSymlinks
RewriteEngineOn
RewriteBase /
RewriteRule ^(.+)\.zig$ /$1.php [NC,L]

21. Delete file extension

This example removes the .php file extension

Options +FollowSymlinks
RewriteEngineOn
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php –f
RewriteRule ^(.+)$ /$1.php [L,QSA]

Like it? Share it.

7 Comments

  1. I really need this tutorials, It is great and very good to know that there is so many things I can do with htaccess. Actually I am trying to learn more about making subdomain using htaccess file and I found this is also more interesting.

  2. Thanks a lot for this useful tutorial about “.htacess”. Your code is really helpful for me.

  3. Thanks for your nice tutorial.

    I think i found an mistake

    in point 8 you wrote:
    DirectoryIndexnewpage.html

    there is an space missing

    • You are correct… Thanks for pointing that out. Article updated!

      • I think the space was between Index and newpage.html, not between Directory and Index ;)

        The correct line should be:
        DirectoryIndex newpage.html

        Also with more than one file, specifying the order in which to look for the pages:
        DirectoryIndex page1.php page2.html page3.htm

        Cheers :)

  4. Great tutorial. It was well organized, nicely sorted and easy to read. I find this tutorial quite a help for better understanding of .htaccess files. Hope to hear from you about .htaccess again.

Leave a Comment Yourself

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>