.htaccess Guide: Tutorial & Code Examples - HostScore (2024)

.htaccess files are plain text documents allowing you to manage how your web server responds to requests. Although originally designed for file access control at the directory level, it also has a number of other uses.

This guide isn’t intended to be a comprehensive documentation on .htaccess. It is meant to serve as a basic introduction and outline for newer users. Although .htaccess can be used for a number of things, that doesn’t mean it always should be.

What is .htaccess?

The .htaccess, or hypertext access file, was originally meant for users to control file access. Using it, you can password protect specific directories on your web hosting server. It is used by many (but not all) web servers in the market such as Apache.

In combination with .htpasswd files you can exercise a high degree of directory access control for multiple users. At the same time, it can also be used to handle redirects, ban specific IP addresses or IP ranges, or even work with custom error pages.

Locating Your .htaccess File

.htaccess Guide: Tutorial & Code Examples - HostScore (1)

Just because it has a use, doesn’t mean that all web hosting plans come with the .htaccess file. If you can’t locate yours – don’t panic, it might simply be hidden. Most of the time though, the file should be located in your root folder.

When using your web hosting file manager, this will generally be www or public_html. If you’re running a few websites from the same account then you might have one in the main directory containing each website.

Most files that start with a ‘.’ are hidden files.If you can’t see .htaccess in these locations, then try to enable the ‘show hidden files’ option in your file manager settings or File Transfer Protocol (FTP) client that you are using.

Using .htaccess – Examples of .htaccess Code

For the purposes of this guide, we will be looking at .htaccess coding in context of Apache web server since it is commonly used. Nginx does not make use of this file.

As mentioned, .htaccess is quite versatile and can be used to achieve a number of things. The first thing you need to do though, is to secure the file. Unless this is done, anyone will be able to view your .htaccess file.

Open the file and add the following code:

<FilesMatch "^\.htaccess">Order allow,denyDeny from all</FilesMatch>

If you do this, anyone trying to view it will simply be shown an error message. Now that you’ve protected the file, let’s take a look at what else it can be used for.

1. Directory Access Control

To prevent unauthorized entry, .htaccess can work with another file called .htpasswd. The latter is where you can store specific user names and their access permissions to specific areas. Unlike .htaccess, you only need one .htpasswd file.

To create the file and add a user:

htpasswd -c /directory/ .htpasswd jamesdean

Once you hit the enter key, you will be asked to provide the password for the username you just defined. When storing the password, it will be hash encrypted – not stored in the form you enter it.

By default all directories are open access. To restrict access to specific directories, you will need to place one .htaccess file in each directory you want to secure. The code in the file will specify various allowances or restrictions. For example:

AuthUserFile /directory/.htpasswdAuthName "Restricted Directory"AuthType Basic<Limit GET POST>require user jamesdean</Limit>

The code above allows access to the specified directory only for user jamesdean. At the same time, it restricts jamesdean’s access to only GET and POST functions.

2. Redirection

This is one of the most common uses of the .htaccess file since it makes redirection very simple. You can choose to redirect anything from a single URL to an entire folder or even another domain:

Redirect URLs:

RedirectMatch 301 /old-page/ https://example.com/new-page/

Redirect folders:

RewriteRule ^/?old_folder/(.\*)$ /new_folder/$1 [R,L]

Redirect domains:

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

When using these lines, you need to ensure that the module needed for handling rewrites is enabled. By default, it is. However, it is good practice to include the code to enable it together with the instructions. For a more complete example:

<IfModule mod_rewrite.c>RewriteEngine OnRedirectMatch 301 /old-page/ /new-page/</IfModule>

3. Custom Error Handling

Making use of custom error handles can help improve your Search Engine Optimization (SEO). Instead of visitors bumping into a generic wall, you can use .htaccess to serve them custom pages depending on the error encountered.

You will need to create one custom page for each custom error you want to handle, then redirect those types of error – one per line in .htaccess.

ErrorDocument 400 /bad_request.htmlErrorDocument 401 /auth_required.htmlErrorDocument 402 /forbidden.htmlErrorDocument 403 /file_not_found.htmlErrorDocument 404 /internal_error.html

4. Hotlink Prevention

When another site creates hotlinks to your images, they’re not only making use of your images, but your bandwidth as well. Even if you’re on a web hosting plan with unmetered bandwidth, it will occupy your server resources.

To prevent image hotlinking:

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

If you want to shame them for trying to abuse your resources, include another line to display an image telling people that the site owner is stealing resources from other sites:

RewriteRule \.(gif|jpg)$ http://www.example.com/angryman.gif [R,L]

5. Block Bad Bots

The problem with bots is that not all are bad. For example, Google crawlers are also bots, but they serve an important purpose. Bad bots, however, often do unsavory things such as scrape data – while taking up your web hosting resources to do so.

Using the .htaccess file is one way of denying access to specific bots. There are a number of ways you can do this either by IP address or user agent, which is sort of an identification tag. IP blocking can be done with individual IPs or with an entire range:

Deny from 123.123.123.123

OR

Deny from 124.124.124.0/255

If you intend to block specific bots based on user agent:

RewriteEngine OnRewriteCond %{HTTP_USER_AGENT} WebReaper [OR]RewriteCond %{HTTP_USER_AGENT} ^VoidEYE [OR]RewriteCond %{HTTP_USER_AGENT} ^AnyBotRewriteRule .* - [F,L]

6. Enable Server Side Includes

Server Side Includes (SSI) allow you to call CGI scripts or even either HTML documents from within HTML content. This can be useful in a number of ways, for example keeping file sizes more manageable, or helping you produce more easily maintainable sites.

You will need to define each type of file you want to enable SSI for:

AddHandler server-parsed .htmlAddHandler server-parsed .shtml

If you find that you’re not able to run CGI files outside the cgi-bin directory, then it will be necessary to enable that:

AddHandler cgi-script .cgiOptions +ExecCGI

Note: This may or may not work depending on policies your web host has in place for its servers. If you get an error from doing this, you will need to contact your support team to see if they can enable it for you.

Conclusion: Use .htaccess Sparingly

Given how powerful this file is, it can be difficult to resist simply adding a few extra lines of code to get things done. However, it needs to be remembered that the .htaccess file is not a main configuration file.

Each time the web server notes a .htaccess file, it has to read and execute it to override the main configuration settings. This read and execute process takes time and resources, which places additional strain on web servers. Where possible, avoid excessive use of this file.

FAQs About .htaccess

Should I use .htaccess?

In a global usage sense the .htaccess file can offer a lot of convenience. However, this comes at a potentially high cost in server resources. Where possible, rely on mains server configuration rather than the .htaccess file.

How do I know if my .htaccess is working?

The simplest way to ensure your .htaccess file is working is to visit the URL of the directory that you’ve placed it in. If it is not working you will likely encounter a 500 Internal Server Error.

Can I have multiple .htaccess files?

.htaccess files can technically be placed in each directory that you want configured. If you run multiple websites, each home directory can have its own file – along with one in every subdirectory beneath it.

What is the rewrite rule in htaccess?

Rewrite is an Apache module that allows you to rewrite URL requests. It simply takes an incoming request and directs it towards one which you have specified to take its place instead.

.htaccess Guide: Tutorial & Code Examples - HostScore (2024)

FAQs

How to write a .htaccess file? ›

Having a dot in front of the name makes the file hidden. Use your preferred text editor, create a file named . htaccess on your desktop or any other local folder, add the desired text and then upload the file using an FTP client. Instructions on how to establish an FTP connection can be found here.

How does an htaccess file work? ›

htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

How to activate htaccess in apache2? ›

Enable the Apache . htaccess File
  1. Use a text editor to open your configuration file: sudo nano /etc/apache2/sites-available/example.com.conf.
  2. After the VirtualHost block () add the AllowOverride All directive as shown below: ...
  3. Save the file, then restart apache: sudo service apache2 restart.
Sep 25, 2017

Where to place an htaccess file? ›

htaccess file should be placed in the web root directory specific to that particular website. If you followed the prerequisites, your web root directory will be in the following location: /var/www/ your_domain /. htaccess .

How do I manually create a htaccess file? ›

htaccess file manually:
  1. Navigate to the WordPress root installation folder (public_html or www). ...
  2. Click the + File button in the upper-left corner to create a new file.
  3. Name the file . ...
  4. Open the file for editing.
Mar 20, 2024

What language is a htaccess file? ›

. htaccess is written in Apache language. Directives is mere a terminology that Apache uses for the commands in its own configuration files.

What is the default .htaccess file? ›

The default WordPress . htaccess file is a configuration file used by Apache web servers to control website access and URL structure. It includes rules for WordPress permalinks and security settings to help prevent unauthorized access and protect against malicious attacks.

How to redirect a URL in htaccess? ›

Explanation of the .htaccess 301 redirect
  1. The first line tells Apache to start the URL rewrite module. RewriteEngine On.
  2. The next line specifies that the next rule only fires when the http host (that means the domain of the queried url) is not www.example.com. RewriteCond %{HTTP_HOST} ^www.example.com$

How to check if .htaccess is enabled or not? ›

Test if . htaccess is working¶
  1. Test. ...
  2. <Directory /var/www/site/example.com/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>
  3. <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^.*$ htaccess_tester.php </IfModule>
  4. <Directory "/var/www/htdocs"> AllowOverride None.
  5. AllowOverride All.

Is .htaccess necessary? ›

htaccess is not required for having a general website. That file simply allows you to make changes in the way your website behaves for example banning people from accessing your site or redirecting an old dead link to a new page. Some software like Wordpress requires settings in the . htaccess file (or httpd.

How do I edit a htaccess file? ›

Right-click on the file, then click on Edit from the menu. A dialogue box may appear asking you about encoding; just click on the Edit button to continue. The editor will open in a new window. Edit the file as needed, then click the Save Changes button.

What is the basic htaccess file? ›

The . htaccess file's basic use is to allow or block access to a certain directory. You can configure it to selectively allow or disallow requests from a certain user. You can also redirect such users to a certain URL.

How to locate .htaccess file in Apache? ›

htaccess file located within the root directory of your website. If you are not sure what a root directory is, then please refer to our article about finding the root directory of your domain. Usually, this file will be hidden as it may be used to compromise your account.

How to create .htaccess file in Apache server? ›

htaccess is a configuration file utilised by Apache web servers to alter a websites functionality.
  1. Open a text editor such as Notepad ++.
  2. From the View menu, ensure that Word Wrap is unchecked.
  3. Click File > Save As.
  4. Set the file type to All Types.
  5. Name the file . htaccess and click Save.

How do I create a .htaccess and .htpasswd file? ›

How to password protect a website folder using . htaccess
  1. Create a file using a text editor such as Notepad or TextEdit.
  2. Save the file as: .htpasswd.
  3. Copy and paste the username/password string generated using our tool into the document.
  4. Upload the . htpasswd file to your website using FTP.

How do you edit the .htaccess file? ›

How To Edit An . htaccess File - Edit htaccess file in cPanel's File Manager
  1. Edit the file on your computer and upload it to the server via FTP.
  2. Use an FTP program's "Edit" mode that allows you to edit a file remotely.
  3. Use SSH and a text editor to edit the file.
  4. Use the File Manager in cPanel to edit the file.

What is the basic .htaccess file for WordPress? ›

In WordPress, . htaccess is a special configuration file that can control how your server runs your website. As one of the most powerful configuration files, . htaccess can control 301 redirects, SSL connections, password protection, the default language, and more on your WordPress site.

Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 6215

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.