An introduction to the htaccess file:The Ultimate Guide (2018 Update)

htaccess file

Browsing through the file manager of your cPanel or hosting account, you may have seen a file called .htaccess. This file governs many configuration settings for the Apache Web Server. Apache is widely used server software for cross-platform operating systems. While the syntax it uses can be a bit confusing at first, the .htaccess file can do many powerful things. Some of its functions include redirection, password protection, restricting access based on certain conditions, and more. This post will look at how to setup an .htaccess file and implement a couple of its most common uses.

 

Initial Notes and Setup

htaccess file

.htaccess is commonly known as a “dot file”, due to it starting with a period or dot. Dot files are almost always some form of configuration file. Dot files can be for an operating system or a piece of software. By default, an operating system hides dot files in finder windows or any sort of system file manager. You typically have to select a “Show hidden files” option from your operating system’s preferences. Or you can use the ls -a command to display all files on the command line.

You can have multiple .htaccess files on a server, and each file always works recursively. This means that each file will effect the directory its located in, as well as all files and subdirectories.

If you’re using FTP to transfer your .htaccess file to a server, you must transfer via ASCII mode. By default, most FTP clients will transfer data via BINARY mode, which is ineffective for transferring dot files. There should be an option to set the transfer mode in your FTP client.

Once you have the file on your server, test to see that it’s doing what it’s supposed to be. If for some reason it seems that no changes have taken effect, it may be due to incorrect file permissions. File permissions for .htaccess should be set to 755. There should be a “File Permissions” option in your FTP client. Alternatively, you can run the command chmod 755 .htaccess in the terminal.

Custom Error Pages

The use of the .htaccess file allows for setting up custom error pages. This allows for more useful messages, in the advent a visitor encounters an error message. (Click to Tweet this Tip) The common “404 File Not Found”, “401 Unauthorized Access” or “500 Internal Server Error” messages can be fairly alarming. Having a way for the user to get back to where they intended to go can be helpful.

You can create your own custom HTML pages for each of the common error types. Additionally, you should place each of them in a directory called error_pages in your root directory. You should name each of the error pages only using its error code (i.e. 401, 404, etc.), followed by the .html extension.

To implement these error pages into your site, add the following code to your .htaccess file:

ErrorDocument 401 /error_pages/401.html
ErrorDocument 404 /error_pages/404.html
ErrorDocument 500 /error_pages/500.html

 

Page Redirection

htaccess file help

Another common use of .htaccess is for page redirects. You can direct from any relative path within your site director. You can also redirect to either an absolute path on your site, or somewhere else entirely on the Internet. The basic syntax to use in your .htaccess file is:

Redirect /directory_to_redirect_from/ https://mysite.com/new_directory/index.html 

 

You should always use a relative path as the source directory. An absolute path should be the directory to re-direct to.

htaccess file: Adding password protection

You can add password protection either to your entire site, or only to specific directories. A protected site or pathway will require a username and password to access. Once landing on a password-protected page, a pop-up from the browser will appear. Additionally, all passwords used in .htaccess get encrypted for added security.

To password protect a specific directory, navigate to that directory and create a new .htaccess file there. You can password protect an entire site by adding the .htaccess file to the root directory. Keep in mind that .htaccess will recursively password protect all files and subdirectories within the main directory.

The basic syntax for adding password protection is as follows:

AuthName "Authorized Access Only"
AuthUserFile /htpassword-filepath/.htpasswd
AuthType Basic
require valid-user

 

AuthName "Authorized Access Only" indicates the name for the protected directory. “Authorized Access Only” will appear in the pop-up upon login.

AuthUserFile /htpassword-filepath/.htpasswd tells Apache where the .htpasswd file is. You should replace /htpassword-filepath/.htpasswd with the actual file path on your server for .htpasswd.

AuthType Basic signifies that Basic HTTP authentication will be employed. This is the most common type of HTTP authentication and more than adequate for most applications.

The last line, require valid-user, indicates that a username and password is needed in order to access the directory. If you would like to require a specific username, you can use require user name. Replace name with the specific username required. This is most often used for admin sections of a site you only want specific users to have access to.

Here’s a cool video showing how to create & edit an .htaccess file by Zac Gordon.

 

.htpasswd

You can place .htpasswd in any directory on most servers, so long as you place the absolute pathway for the file in .htaccess. Using a relative pathway or a URL will not locate the file. In some instances .htpasswd will need to be in the same directory as .htaccess, however. Additionally, you can name .htpasswd something else. Although this is a naming convention that Apache will automatically understand.

To add a password to .htpasswd, use the following syntax:

username:encryptedpassword
admin:fs424sJK/67JGmn

You can have multiple usernames and passwords saved in a single .htpasswd file, each on their own line. Each username and password pair should be on the same line with no spaces, separated only with a colon.

Linux servers require that you use a password encryption service to encrypt the password. There are many such applications and websites that can do this for free. One option worth mentioning is ionix’s DirectoryPass.

Keep in mind that .htaccess does not allow for logout functionality. Once the correct login credentials have been input they get saved in the web browser’s cache until you quit the browser. Re-opening the page after quitting the browser will require that you enter the credentials again.

Denying access by IP address

One useful tool offered by .htaccess is the ability to block visitors based on their IP address. In this way, you can block certain visitors altogether. (Click to Tweet this tip) Alternatively you can block from certain sections of the site, by only adding an .htaccess file to a specific directory.

In order to block visitors based on their IP address, use the following syntax:

order allow,deny
deny from 345.4.5.0
deny from 754.53.8.
allow from all

The code in the example instructs Apache to deny access from the IP addresses 345.4.5.0 and 754.53.8. In the third line, the IP address 754.53.8 does not include a fourth group of digits, so any IP address that matches the first three would get blocked. This means that 754.53.8.2, 754.53.8.4, etc. would all get denied access to the site.

If you only want to allow access from specific IP addresses, rather than blocking, the syntax is very similar. You can use the code below:

order allow,deny
allow from 345.4.5.0
deny from all

In this code, the only IP address that can access the site is 345.4.5.0 — all other IP’s will get denied.

In both cases (setting allowed or blocked IP addresses), you can add as many records as you like, each on its own line.

When an IP gets blocked, visitors will get shown a ‘403 Forbidden’ error message. As we saw before, you can customize Error Pages in order to provide more human-readable information to the visitor.

Preventing Hot linking

When another site sources assets from your site (such as images, video, CSS files, etc.), this unnecessarily uses up your bandwidth. This can lead to higher hosting costs without any attribution or benefit to you.

Fortunately, .htaccess has a way of circumventing this from happening, disallowing other domains from displaying your content:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mycoolsite.com/.*$ [NC]
RewriteRule \.(png|jpg|mp4)$ - [F]

 

Above, .htaccess disallows .png, .jpg or .mp4 files to get linked from a domain other than https://www.mycoolsite.com. You can specify other file formats to disallow (such as .css, .mp3, etc.). Of course, you will want to switch out the code with your own domain name.

To take it a step further, in the advent that an external site tries to link to your content, you can provide an alternative image or message to be displayed in its place (such as an image that says “Sorry, the content you are trying to access is from mycoolsite.com”):

If an external site tries to link to your content, you can provide an alternative image or message to get displayed in its place. An example is an image that says “Sorry, the content you are trying to access is from mycoolsite.com”.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?mycoolsite.com/.*$ [NC]
RewriteRule \.(png|jpg|mp4)$ https://www.mycoolsite.com/hotlink-error-message.jpg [R,L]

This will display hotlink-error-message.jpg whenever someone tries to link to .png, .jpg, or .mp4 files from mycoolsite.com.

Resources

Post a Comment

Comments are moderated. Your email is kept private. Required fields are marked *

© 2018 Sunlight Media LLC - Web Design Company