The htaccess file The Ultimate Guide (2021 Update)

The htaccess file: The Ultimate Guide (2021 Update)

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

Page RedirectionAnother 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

Denying access by IP addressOne 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.  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.

htaccess Redirect to HTTPS

When you add an SSL certificate to your site, your server will continue to serve the HTTP version of all your web pages. This is why you need to redirect HTTP to HTTPS, forcing SSL on your site.

Note that one important function that you can perform through .htaccess is the 301 redirects, and this can permanently redirect an old URL to a new one. It is simple to activate the feature in order to force HTTPS on all the traffic coming to your site by following these easy steps:

  1. In your hosting panel, go to File Manager and open .htaccess in the public_html folder. And if you cannot locate it, you should create or unhide it.
  2. After that, scroll down to find RewriteEngine On and then insert these lines of code just below;
  3. htaccess Redirect to HTTPSNow save the changes.

htaccess WordPress

You should know that in WordPress, .htaccess is one of the special configuration files that can control how your webserver runs and manages your site. The htaccess file is one of the most powerful configuration files and can control SSL connections, 301 redirects, password protection, the default language, and a lot more on your WordPress website.

It is worth noting that the use of .htaccess configuration files became more popular as they could be easily used to override international server settings pertaining to access to directories. In recent times, however, .htaccess can override several other configuration settings.

htaccess File Examples

you will be happy to know that a vast amount of configuration possibilities can be easily achieved within the .htaccess file.

Block IP Addresses

Are you receiving spam traffic? Perhaps, your site is suffering from hacking attempts or abuse from specific IP addresses. If that is the case, you can take action with your .htaccess file. You can easily block traffic from that IP address using a code in your .htaccess file.

To block a particular or specific domain, you can add the following to your website’s root .htaccess file:

Deny from 123.123.123.123/255.255.255.0

After that, change the IP address as well as netmask values in order to match the domain that you wish to block.

Prevent Image Hotlinking

You should know that image hotlinking happens when somebody embeds an image on your site into their own. And this can be very problematic (not merely from a copyright perspective) since it means that your server has to potentially work overtime in order to serve up images on somebody else’s website.

The best thing is that you can easily stop this by using your .htaccess file and block a person from embedding your copyrighted images on their site.

By entering the following lines into an .htaccess file, you can easily prevent hotlinking to your site:

htaccess-file-Block IP Addresses

You can also use the following code:

htaccess-file-Block IP Addresses

Where is the htaccess File?

Did you know that almost all websites, including WordPress websites, have a .htaccess file that you can find in the central (or root) directory? And this htaccess file is hidden and does not have an extension.

Although the file is usually hidden, the .htaccess file location is often found in your site’s public_html folder.

What should be in a .htaccess File?

The file should contain rules that give your site’s server various instructions. Keep in mind that just about every website has an .htaccess file, and it is located in the central directory or ‘root.’

Advantages and Disadvantages

You will be happy to know that .htaccess files are timely read on every request. As a result, any changes you make to these files result in instant effect.

This is unlike global settings, which usually require the server to restart. Also, note that the .htaccess files enable each user to quickly set their permissions for a server that has many users.

However, there’s a big catch. As all requests require the server to read all of the .htaccess files, note that it is likely to lead to moderate to severe performance issues if there’s considerable load.

And that is not all; decentralizing all the settings to various users may lead to multiple security issues, particularly if these .htaccess files aren’t configured correctly.

Things to Look Out for

While a .htaccess file can be immensely useful, and you can use it to make a marked improvement to your website, there are two things that it may influence.

Speed

The .htaccess files may slow down your web server. Note that for most servers, it will likely be an imperceptible or minor change. This is simply because of the location of the page.

You should know that the .htaccess file affects all the pages in its directory as well as all of the directories under it. This means that each time a page loads, the webserver scans its directory and all above it until it finally reaches the .htaccess file or the highest directory.

Security

Did you know that the .htaccess file is considerably more accessible compared to the standard apache configuration? Also, the changes are made instantly. Note that granting users the permission to make alterations and changes in the .htaccess file gives them too much control over the web server itself.

Editing htaccess Files

Editing htaccess FilesDid you know that editing the .htaccess file is risky? This is because you could delete code you should not. You could also add incorrect code or make some other mistake that breaks your website. In order to mitigate these risks, it is vital to take at least one precautionary step before making any direct edits to your htaccess file.

You can backup your website so that you can easily restore an earlier version of your website if you make a mistake. On the other hand, you can use a staging website to test your edits before you push them live on your public-facing website.

It is best to create a backup .htaccess file and then download it to a computer. This ensures that if your edits in your default .htaccess file do cause any problems or issues, you can rely on and upload the backup file.

 

Conclusion

It is no secret that learning to work directly with your site’s files is a vital step in your journey to becoming a reliable web developer. And the .htaccess file is an excellent place to start, as it is a simple file that you can use for a wide variety of applications.

Note that every time you understand and learn more about what happens behind the scenes with your website, you get closer to becoming an effective webmaster and have the potential to streamline and enhance your website’s functionality.

 

Author Bio

Angelo has been involved in the creative IT world for over 20 years. He built his first website back in 1998 using Dreamweaver, Flash and Photoshop. He expanded his knowledge and expertise by learning a wider range of programming skills, such as HTML/CSS, Flash ActionScript and XML.

Angelo completed formal training with the CIW (Certified Internet Webmasters) program in Sydney Australia, learning the core fundamentals of computer networking and how it relates to the infrastructure of the world wide web.

Apart from running Sunlight Media, Angelo enjoys writing informative content related to web & app development, digital marketing and other tech related topics.

Post a Comment

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

© 2021 Sunlight Media LLC | 811 W 7th St. Level 12, Los Angeles CA, 90017 | 323.868.3581