Home / Articles / Web Hosting Guides / The Basics of .htaccess: How to Use & Examples

The Basics of .htaccess: How to Use & Examples

The Basics of .htaccess: How to Use & Examples

What is an .htaccess file?

The .htaccess file is an Apache HTTP Server (normally just called Apache) configuration file. The file is extremely powerful and can be used to help control multiple facets of web pages that are served up by Apache. This includes things like managing redirects, hotlink protection and more.

Where is the .htaccess file?

There should be one .htaccess file in your web host root folder – the folder (usually /public_html or /www) that holds the content of your website.

You can have more than one .htaccess file on your hosting account, but each directory or folder can only have one. For example, you can have separate .htaccess files in your root folder and another in a sub-folder. This allows you to set different server behavior based on directory structure.

The .htaccess file is powerful but can be accessed and modified if not protected correctly. Make sure that you take steps to prevent access to this file.

Your .htaccess file may be hidden

First of all .htaccess is an Apache file, this means you can only find it in an Apache server.* Stop searching if your host is running on a different web server software (ie. Microsoft IIS or NGINX).

File names that begin with a dot usually hidden files. This means they are not typically visible by default.

To view this file, simply turn on “Show Hidden Files” in your FTP client or Hosting File Manager (see image below).

Find .htaccess file - How to show hidden files in cPanel file manager
Example – Display your hidden files by enabling this option in cPanel File Manager.

You may feel that the .htaccess file is an inconvenience since it requires coding but consider the user who needs to establish the same server behaviour across multiple sites. All that person will need to do is duplicate the .htaccess file.

.htaccess files are server configuration files and since they address behavior directly, there isn’t a need for something to be run each time a request is made. It is therefore much less resource intensive as using a plugin, for example.

* Note: Apache has about 22.8% market take up rate for the top million sites based on W3Techs May 2022 report. Most popular hosting brands mentioned at WHSRA2 Hosting, BlueHost, GreenGeeks, Hostinger, InMotion Hosting are powered by Apache. 

Using .htaccess File – Real Life Examples & Code Samples

Although there is a dot in front of the filename, htaccess is the name of the file and the dot does not make it an extension. Specifically, it is this exact filename that Apache looks for when it is run. Anything inside the .htaccess file sets parameters for Apache to enable or disable functions or even execute specific tasks when certain conditions are met.

For example, based on instructions contained in the file, Apache can automatically load custom error pages if your website visitors are looking for a resource which isn’t there. Each error type has its own code and each of these can be redirected individually.

There is a huge list of what can be done using the .htaccess file and today I’ll be sharing some of these with you.

1. Managing Custom Error Pages

Using .htaccess ErrorDocument 404 to redirect your users to another page.
Examples of some creatively customized 404 Error pages

When left at default settings, most web server software sends a very bleak-looking error page to your visitors. If you want to display a more user-friendly (or at the very least, presentable) error page then you’ll need to use custom error document handling in your .htaccess file.

Let’s say that you’ve designed a custom 404 error page called “404.html” and saved it into a sub-folder in your web directory called “error_pages”. Using the following line of code in .htaccess, you can call that page up whenever a 404 error is encountered by a visitor;

ErrorDocument 404 /error_pages/404.html

Using this technique, you can save customized copies of each individual error type you want to account for and set them up to be called by including the necessary code in your .htaccess file. The most commonly encountered error codes include;

  • 400 – Bad request
  • 403 – Forbidden
  • 404 – File Not Found
  • 500 – Internal Server Error
  • 503 – Service Unavailable

2. Handle Redirects

There may be occasions when you want to set a blanket redirect so that you can direct your visitors to specific pages without them knowing. For example, if you originally used HTTP but have since then installed SSL and moved to HTTPS, you’d want all your users to use the HTTPS version of your site.

In this situation, what you need to do is make use of the Rewrite rule;

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]

The code for this can be modified depending on your needs. For example, if you want to redirect users from your old domain to a new one instead, then you would use;

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

There are many variations how you can set up redirects. Details of the syntax for Rewrite can be found in the Apache documentation pages.

One of the most useful things that redirects can do for you is to help you guide search engines to pages which you’ve moved. Normally, search engines will index links and if they can’t find the right pages there they will assume the content is gone.

By using a redirect, you can easily move content and let web crawlers know where to find the content they have previously indexed. To do so, use;

Redirect 301 /archive/ /past-entries/

The 301 instruction not just lets users access the old content seamlessly, but also serves as an instruction to web crawlers that the content is moved permanently. This helps them by allowing them to re-index links quickly.

3. Increase Website Security

I find that many new website owners tend to rely overly much on external tools to increase their website security. While it is true that there are a ton of great applications out there, you can start with the basics in your .htaccess file.

Password Protect Directories

To do this you’ll need two files, .htaccess and .htpasswd. The .htpasswd file includes some encryption, so use a tool like Htpasswd Generator to create the file. The .htaccess file should include this code;

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /path/to/.htpasswd
Require valid-user

Disable Directory Browsing

This is one of the easiest to do and only needs two lines of code to be included in your .htaccess file;

# Disable directory browsing
Options -Indexes

Block Specific IPs

To block individual IPs from visiting your site, add the following code to your .htaccess file;

Deny from XXX.XXX.XXX.XXX

Where you replace XXX with the numeric IP values. There are variations of this code that can be used to block a range of IP addresses or multiple IP addresses as well.

4. Hotlink Protection

Hotlinking occurs when other websites link to images that you are hosting. This is undesirable because they are making use of both your space as well as bandwidth. To prevent image hotlinking, add the following to your .htaccess file;

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)example.com/.*$ [NC]
RewriteRule \.(gif|jpg|jpeg|bmp)$ - [F]

The last line of that code is where you specify what files you want to block sites from hotlinking. It is basically instructing Apache to block all links to those files which are not from the domain name http://www.example.com/.

Many people who hotlink often don’t check their posts again, so if you really want to embarrass them, you can display a custom message to sites that are trying to hotlink;

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)example.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.example.com/stopstealing.gif [R,L]

5. Protecting the .htaccess File

By now you’re realizing how useful a tool the .htaccess file really is. Since you’ve come to that realization, it’s time you thought about protecting this valuable file! If you’re using a .htpasswd file, then you’ll probably want to shield that as well and the way to do both is to;

# protect .htaccess and .htpasswd

<Files ~ "^.*\.([Hh][Tt])">
Order allow,deny
Deny from all
Satisfy all
</Files>

Do note that on most secure servers these files are already protected. Before you add this code check to see if you can access the files in a browser window. Simply type in the URL and add a /.htaccess behind to see if you can view the file. If you can’t you will likely be shown an error message.

6. Setting Your Server Time Zone

If you notice that for some reason or other, times on your server seem to be off a little then you may need to force a time zone using the .htaccess file. This is something that’s again easy to do and needs only a single line of code;

SetEnv TZ America/yourtimezone

There is a huge list of time zones available and you can find the closest match to yours by referring to the list of supported time zones.

Embrace the Power of .htaccess

The samples I’ve shown here are only the tip of a very large iceberg. It gives web hosting users much greater power over their sites than would normally be allowed through a control panel and give them a wider array of tools to work with.

Learning to use the code is merely a step away with the power of Google, and the best thing about it is that you only need to pick and learn the things you need to use.

.htaccess File FAQs

Do I need a .htaccess file?

No, .use of .htaccess is not mandatory. However, it is one of the only ways shared hosting users can get some control over their web hosting server. If you don’t plan on making server configuration changes on shared hosting, the file is unnecessary.

What does .htaccess file contain?

Since the .htaccess file is for server configurations, it contains code with related instructions. For example, the line “SetEnv TZ America/yourtimezone” will allow you to set the server time zone per your preference.

How do I create a .htaccess file?

The best way of creating a .htaccess file is by using a plain text editor. For example, you can use Microsoft NotePad on your local machine then upload it to your web hosting server. Alternatively, most web hosting file managers will also allow you to create plain text files.

Does WordPress have a .htaccess file?

The .htaccess file isn’t directly related to WordPress since it is meant for server configurations. Your WordPress website may or may not have one. If it is not present, you can still create and use a .htaccess file manually.

Read More

Photo of author

Article by Jerry Low

Keep Reading