.htaccess tutorial and cheat sheet | Tips & Tricks

Welcome to our . ! . is a tiny but powerful plain text file that you can use to make configuration changes to Apache on a per-directory basis. It acts as a middleman between you and the Apache web server.


Learn to modify the .htaccess file and you’ll have the power to direct your users to the right page, outsmart hackers, and make tweaks to enhance your site’s performance.

By modifying the .htaccess file, you can make changes to the behavior of your website that would otherwise require higher access levels than your hosting account may offer.

This .htaccess tutorial will explain how to harness the power of .htaccess to accomplish common tasks. Some of the magic it can achieve includes:

  • URL redirection and rewriting — Make sure your users get exactly where you want them to go.
  • Security — Restrict access to particular files or directories or block unwanted access from your site.
  • Site optimization — Add tweaks that enhance site performance.

Now let’s get into our .htaccess tutorial.

Placing the .htaccess file

An .htaccess file is most often located in the root of the website it controls. From there, it will affect all subfolders in the site.

However, you can also put an .htaccess file in a particular subdirectory farther down in your site’s structure. This is useful if you only want to affect a portion of your website, as the file will only affect the directory it’s in and those beneath it.

It’s permissible to have multiple .htaccess files on a site, though for ease of maintenance, webmasters often use a single file located in the site root to make all necessary changes.

Editing .htaccess from cPanel

Any text editor can be used to modify .htaccess, including the one built into cPanel’s File Manager. It’s a convenient way to edit .htaccess files.

1. Log into cPanel.
2. Under the Files section, click on the File Manager icon.

htaccess Tutorial File Manager

3. In the popup window, select the Document Root for the site you are working on and make sure Show Hidden Files is checked. Note that some versions of File Manager may have a slightly different interface but will require the same setting selections. If the window below doesn’t pop up automatically when you click on File Manager, look for a Settings icon and click on that to reach these settings.

htaccess Tutorial Directory Selection

4. Look for the .htaccess file and right click on it. From the drop-down menu that appears, select Edit.

htaccess Tutorial Edit

5. You will now be in the text editor, where you can make and save changes.

Related: cPanel and tricks that will make your life easier

Don’t forget to create a backup.

If you mess up your .htaccess file you can easily break your website, so create a backup first. If you do crash your website and for some reason don’t have a backup, don’t panic — simply rename .htaccess to .htaccess.old and that should bring it back up.

What’s the dot at the beginning of the filename for?

The dot at the beginning of the file name tells Unix/Linux systems to hide this file, so when using file manager, be sure to tick the checkbox for “show hidden files” or you might not be able to find it.

Putting .htaccess to work: URL redirects and rewriting

Sometimes you need to redirect users to a page other than the one they linked to from their web browser. Perhaps that page no longer exists, or maybe you want to forward them from a non-WWW URL to a WWW URL. This is where redirects and rewriting come in.

Note that a lot of these examples begin with the directive RewriteEngine on. You only have to use this once and it will apply from then on in the file unless you turn it off.

Force WWW or non-WWW using .htaccess

For search engine optimization, it’s often recommended to stick strictly to a WWW or non-WWW version of your website to achieve a stronger search engine presence. To accomplish this, add the following lines (be sure to change example.com to your site name):

#Force WWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

Force HTTPS

Use this to redirect a non-HTTPS URL to an HTTPS request:

#Force WWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

Force trailing slash

Use this to redirect URLs that don’t contain a trailing slash to the same URLs with a trailing slash (i.e. from http://example.com/somepage to http://example.com/somepage/):

RewriteEngine on
RewriteCond %{REQUEST_URI} /+[^.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Remove trailing slash

To strip off trailing slashes, use this:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

Redirect a single page

Automatically a single URL to a different URL:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

Redirect entire site to a new domain

If you’re moving your site to a new domain, but all the links will otherwise remain the same, you can do this on the old domain:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^OldDomain.com
RewriteRule ^(.*) http://NewDomain.com/$1 [P]

Alias to “clean” URLs

Add these lines if you want to use “clean” URLs – i.e. http://example.com/articles instead of http://example.com/articles.php (in the example, replace .php with the extension you want removed):

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

Improving security using .htaccess

.htaccess can be used to protect single files or an entire directory by denying access entirely or requiring a password. You can also block those sneaky hotlinkers and keep them from using your bandwidth.

Password protect a single file

To password protect a single file in an otherwise public folder, first you need to create an .htpasswd file containing the user name and encrypted password for permitted logins.

An easy way to do this is using a free webmaster tool like the one at 4WebHelp. Once you save the .htpasswd file to your system, you can use .htaccess in conjunction with it. Here’s the complete process:

1. Use a webmaster tool to create a username:encrypted_password combo. The line produced will look something like this: User_Name:14fcYjcLcsbMU Copy the resulting line and save it to a text editor.
2. Log in to cPanel, and under the Files section, click File Manager.

htaccess Tutorial File Manager 2

3. In the popup window, select the Home Directory and ensure that Show Hidden Files is selected. This is where you will put the .htpasswd file. This location is hidden from the public and isn’t accessible via a URL, so it is more secure.

htaccess Tutorial Directory Selection 2

4. You are now in your home directory. Click the +File link in the top left corner to create a new file there. In the popup window, enter .htpasswd as the file name and click Create New File. Leave the second line blank. It will default to the current, home directory.

htaccess Tutorial New File

5. A directory listing of your home directory will be displayed. Note the path displayed in the left-hand pane of file manager as you will need it later. It will be something like /home/username. Scroll down until you find the file you just created and right click on it. (If you don’t see any files beginning with a dot, you probably didn’t select “show hidden files” — you can correct this by clicking on the settings icon and doing it there.)

htaccess Tutorial Edit 2

6. The file editor will open. Paste the line you saved from the password encrypter into the new file and save it. You are then ready to move on to the .htaccess modifications.
7. Add the following to your .htaccess file using the procedure described at the beginning of this article. Replace /home/username with the path you noted earlier. Replace mypage.html with the name of the page you want to password protect. You can also change “Login Required” to something different, like “Members Area” — this will be displayed on the login prompt.

AuthUserFile /home/username/.htpasswd
AuthName "Login Required"
AuthType basic

Require valid-user

8. Click Save Changes. Then visit your site and try to access the file to verify the protection is working. If you visit the page a second time, you might not be prompted for the login as your browser will likely remember it.

Related: How to use Bing Webmaster Tools to improve your site’s SEO

Password protect a directory

The procedure to password protect an entire directory is similar to that for protecting a file:

  1. Create an .htpasswd file as described in the item above, Password protect a single file. Stop after step 6, before making any changes to .htaccess.
  2. Create a new .htaccess file inside the subdirectory you want to protect and add the following lines:
AuthUserFile /home/username/.htpasswd
AuthName "Login Required"
AuthType basic
Require valid-user

Note that you can also protect a directory via cPanel, without using .htaccess.

Deny access to a single file

To prevent all users from accessing a particular file, add the following lines, replacing the filename with the name of the file you want to protect:


order allow,deny
deny from all

Deny access to hidden files and directories

Use this to prevent hackers from directly accessing files that should remain hidden — i.e. those that begin with a dot. These lines will give the hacker a 404 not found error rather than an access denied, so the hacker will have no clue.

RedirectMatch 404 /..*$

Block image hotlinking

Keep people from stealing your bandwidth by linking to your images:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourdomain.com [NC]
RewriteRule .(jpg|jpeg|png|gif)$ - [NC,F,L]

You can also modify the above to show an alternate image instead of the one that’s hotlinked, typically one that says something like “No hotlinking allowed!” To do so, change the last line to this:

RewriteRule .(jpg|jpeg|png|gif)$ http://www.yourdomain.com/no-hotlinking.jpg [R,L]

Site optimization using .htaccess

Next up in our .htaccess tutorial: Using .htaccess to improve site performance. With it, you can enable file compression and exert some control over caching, which can substantially speed up your site.

Compress text files using gzip/deflate

The Apache mod_deflate module can compress data using gzip compression before transmitting it to the user. This can reduce the amount of bandwidth your site uses, although it won’t necessarily speed up your site. The module is already enabled on most servers, but you’ll need to add the line below to actually use it:

AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript

Set expires headers

Browser caching speeds up your website significantly. In order to capitalize on this, you have to set an expiration date for each type of file you want cached. Use the below code as a starting point. You can set the duration of the cache for each item using all the standard time units, including years, months, weeks, days, hours, minutes and seconds.

ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"

Limit file upload size

To prevent users from uploading massive, resource-hogging files, limit the file upload size using .htaccess. Enter the size limit in bytes.

LimitRequestBody 1048576

Related: Speeding up WordPress with memcached and W3 Total Cache

Miscellaneous

Here are a few more handy things you can do with .htaccess:

Change default index page

By default, your server will attempt to display index.htm, then index.html, then index.php, and then default.htm as the first page of your website. You can override this to set a default index page as follows (replace first.html with the page you want displayed):

#Set default index page
DirectoryIndex first.html

You can add an entire list here, also, which the server will go through in order until it finds one it can serve up.

#Set default index pages
DirectoryIndex index.php index.htm index.html home.html

Change server time zone

Set your server time zone to anything you’d like. The code below sets the server to New York time. A handy list of time zones is located here.

#Set default index pages
DirectoryIndex index.php index.htm index.html home.html

Custom error messages and pages

It’s very easy to change error handling by using the ErrorDocument directive. You can specify a message or redirect to a file. The below will display a page named 404.html when a “page not found” error is thrown:

ErrorDocument 404 /404.html

You can also directly use text, like this (note that the message is enclosed in quotes):

ErrorDocument 404 “Oops, that page was not found. We have recorded the error and will look into it.”

You can also add lines for other server error codes. Here are a few more examples:

ErrorDocument 403 "Sorry, you are not permitted to access this."
ErrorDocument 404 /404.php
ErrorDocument 500 "Oops! Our server encountered an error. Try again later."

A list of server error codes can be found here.

This is just the tip of the .htaccess iceberg

The above examples cover the most common uses of .htaccess, but there are even more. Here are some additional .htaccess sheets from around the web:

  • htaccesscheatsheet.com
  • an .htaccess cheatsheet in PDF format
  • mod_rewrite cheatsheet

While .htaccess offers a powerful and fairly simple way to interact with Apache, note that some of these changes can also be accomplished via the cPanel interface. In those instances, the route you choose is a matter of personal preference.

Have fun and remember to back up your original .htaccess file just in case.

The post .htaccess tutorial and cheat appeared first on Garage.

Advertisements

You might also like More from author

Comments are closed.