Beginners guide to htaccess file

What is a .htaccess file?

.htaccess stands for Hypertext Access.   It creates a set of rules for the directory that it is in and all sub-directories that are contained in that directory.  A file named “.htaccess”, on an Apache based web server, will allow you to configure specific settings for how you’d like your website, or certain files within your website, to behave.

Where is my .htaccess file?

The dot in front of “.htaccess” indicates that this file is ‘invisible’. Therefore you may have to configure the application you’re using to show invisible files.

hta2

In your file manager, the first page that shows on the right hand side will allow you to show hidden files.

hta4

I still can’t find my .htaccess file?

The .htaccess is not created by default and may not be created yet. You can create one by just creating a new file and naming it exactly “.htaccess”. This naming convention is very important. If the file is named something like “htaccess.txt” or “ht.access” the system will not know what to do with it, and will not process any configurations within.

What can I do with my .htaccess file?

There are endless changes you can make to your .htaccess file to customize the way your website behaves. Some of the more common customizations include Directory Indexing, Custom Error Pages, SEO, and URL Rewriting.

Directory Indexing

By adding a directory index to the .htaccess file you can use different files as your main home page. So when someone visits your site you can have “home.html” be the first page they see instead of “index.html”.

DirectoryIndex home.html index.php index.html default.htm

In this instance the first page the server would look for would be “home.html”. If it couldn’t find “home.html”, it would then look for “index.php”, then “index.html”, and so on.

Custom Error Pages

There are many errors that a user can encounter when surfing the web, each of these can have different implications and each of them are caused for different reasons. The most common errors you will run into are:

  • 400 – Bad Request
  • 401 – Authorization Required
  • 403 – Forbidden
  • 404 – File not Found
  • 500 – Internal Server Error

For each of these errors you can create a separate line in your .htaccess file to tell that error what file to direct to. For example, if someone searches for a page that doesn’t exist, and you would like them to be redirected to your own custom ‘page not found’ page, instead of the default 404 – File not Found page. You would add the following to your .htaccess file.

ErrorDocument 404 /filenotfound.html

In the above example any normal 404 error that a user might receive will instead redirect to “filenotfound.html”. So similarly if you wanted to redirect any “500 – Internal Server Error” to a custom page:

ErrorDocument 500 /mycustompage.html

SEO

Using a site map, as well as custom error pages will result in better “Search Engine Optimization (SEO)”. This is because a site map will allow for users as well as search engines to better find the information they are looking for within your site. If a user gets a “500 Internal Server Error”. They’re likely to leave the site and not return, however if that same error directs to a custom page that still has your site map they’re much more likely to remain on your site. That same “500 Internal Server Error” will cause problems with search engine rankings unless you’ve specified to direct to a custom page whenever these errors occur.

URL Rewriting

URL Rewriting is the rewriting of the main URL seen at the top of each page. In most dynamic websites the URL is used to pass information from one page to the next. Which ends up making URL’s look like this:

http://www.website.com/show_a_product.php?product_id=12

Using URL rewrites though you can clean this up to look like this:

http://www.website.com/products/12/

Rewriting these URLs makes your site more memorable, and it’s hard direct someone to a specific place without an actual link. So if you were to read the URL over the phone for example it would be much harder to do without rewriting. After Rewriting the URL though it’s much easier to read out, and is generally just much cleaner and shorter.

You also have the ability to make the URL descriptive. Instead of using ‘products’ and ’12′ or similar. You can use actual descriptions of the products you might have on your site.

http://www.website.com/clothes/shoes/

These types of URL’s are not understood by the server unfortunately. So we need to create a correlation between the URL that we want, and the URL that the server understands. This is where URL rewriting within the .htaccess file comes in to play.

The first step in rewriting URL’s is to make sure the server knows that you plan on rewriting the URL’s, as this is not default for the server. This needs to be done before any URL rewriting can occur, so the first thing we need to add to our .htaccess file is:

RewriteEngine On

Now that the server knows that the rewrite rules are turned on we will create a rule to rewrite a URL.

RewriteRule    ^products/?$    show_a_product.php    [NC,L]

In the above rewrite rule let’s go over each piece individually:

  • RewriteRule – This piece is telling the server that we are creating a new rule for rewriting URLs.
  • ^products/?$ – This is the ‘Pattern’ part of the rule, this piece of the rule tells the server what you want the pattern for your rule to look like. The ‘pattern’ piece has some special symbols.
    • . (dot) – any character
    • * (asterisk) – zero of more of the preceding
    • + (plus) – one or more of the preceding
    • {} (curly brackets) – minimum to maximum quantifier
    • ? (question mark) – ungreedy modifier
    • ! (exclamation mark) – at start of string means “negative pattern”
    • ^ (caret) – start of string, or “negative” if at the start of a range
    • $ (dollar sign) – end of string
    • [] (brackets) – match any of the contents within
    • - (dash) – range if used between brackets
    • () (parenthesis) – group, backreferenced group
    • | (pipe) – alternative, or
    • \ (backslash) – the escape character itself
  • show_a_product.php – This is the “substitution” pattern. this is the link that the server will understand
  • [NC,L] – These are the “Flags”, these tell the server how to apply the rule we’re making. In this case “NC” tells the server that this rule is not case sensitive, and “L” tells the server not to process any additional rules, if this one is used.
  • # – Anything in a .htaccess file that resides after a (#) is considered to be a comment, so nothing after this will be executed.

So if we wanted to create an entire rewrite rule within .htaccess it might look like the following

RewriteEngine On
RewriteRule    ^products/([0-9]+)/?$    show_a_product.php?product_id=$1    [NC,L]    # Handle product requests

URL rewriting has too many utilities to cover entirely in this introduction to .htaccess. But here is a list of some useful rules:

  • To redirect an old domain to a new domain:

RewriteCond %{HTTP_HOST} old_domain\.com [NC]

RewriteRule ^(.*)$ http://www.new_domain.com/$1 [L,R=301]

  • To redirect all requests to show “www” in front of the URL

RewriteCond %{HTTP_HOST} ^domain\.com [NC]

RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

  • To redirect all requests to take away “www” in front of the URL

RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]

RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

  • Redirect old page to new page within the same site:

RewriteRule ^old-url\.htm$ http://www.domain.com/new-url.htm [NC,R=301,L]

URL Redirects

Web masters and/or developers will sometimes want to create permanent or temporary redirects for their domains to another domain. This is called a 301 or 302 redirect and uses very simple code:

Redirect 301 / http://destinationdomain.com/
Redirect 301 /somefile_or_folder/index.html http://destinationdomain.com

By just copying the code above and replacing destinationdomain.com with the actual name of the domain you wish to redirect to, your traffic will start redirecting to the destination domain with in a few minutes. There is also a redirect that’s able to be used for temporary redirects. These are in place to route traffic to a similar or different domain while tasks are being completed on the routed domain. The code is the same but the 301 becomes 302:

Redirect 302 / http://mydomain.com/
Redirect 302 /somefile_or_folder/index.html http://destinationdomain.com

There may be times where you have a parked/pointed domains you wish to point to a main domain or elsewhere temporarily. This helps with search engines not treating the domains as duplicate content. They are able to achieve this by adding the below code into their .htaccess file:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?myparkeddomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^(www.)?myparkeddomain-2.com$
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]

 Another more basic solution is:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.mydomain.com$
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]

 Using any of the above code will help redirect your domain(s) to wherever you want them to go. The .htaccess file code is universal and can be used on any domain and on any server. Be sure to change any sample code to match what domain name you are redirecting is and where you want your traffic to go. Also keep in mind the server file structures are different on windows machines as they use web.config files and not .htaccess files.

Summary

At this point you should have at least a general understanding of how to find or create your .htaccess file. As well as a few tricks to make your site easier to navigate for the end user. There are endless ways to modify your .htaccess file, and no one way works for everyone. But hopefully this guide will you help you find your way.

Was this article helpful?

Yes (67)
No (2)

We're sorry you didn't find this article very helpful. Please help us improve it by leaving your feedback below.

Error