How To Use the .htaccess File
Table of Contents
Introduction #
An .htaccess
file is used for an Apache web server as a way to configure the details of your website without altering the server configuration files. This file begins with a period to signify that it’s hidden within the folder. An .htaccess
file can be used to load customized error pages (such as 404 pages), create URL redirects, implement password-protected authentication for specific directories on your server, and more.
In this tutorial, you will learn how to enable, create, and use an .htaccess
file, as well as some common uses and the impact on speed and security.
Prerequisites #
If you want to practice using an .htaccess
file by following the examples throughout this tutorial, you will need:
One Ubuntu 20.04 server set up with a non-root user with sudo
privileges and firewall enabled. You can do this by following the Ubuntu 20.04 initial server setup guide.
The Apache web server installed on your Ubuntu server. Learn how to set it up with our tutorial on How To Install the Apache Web Server on Ubuntu 20.04. Be sure to complete Step 5 and have a virtual host file for your domain. This tutorial will refer to your_domain as an example throughout and use /etc/apache2/sites-available/your_domain.conf
for the virtual host file.
If you would like to practice with a domain (optional), you can set one up by purchasing a domain name on Namecheap, get one free on Freenom, or use the domain registrar of your choice. You will also need both of the following DNS records set up for your server: two A records, one with your_domain
and one with www.your_domain
pointing to your server’s public IP address. Follow this introduction to DigitalOcean DNS for details on how to add them.
If you would also like to secure your virtual host, you can do so with a free trusted certificate, such as in our Let’s Encrypt guide for Apache. However, if you do not have a domain, you can use a self-signed certificate instead. This provides the same type of encryption, but without domain validation. Follow our self-signed SSL guide for Apache to set this up.
Once you’re done setting up, you can practice enabling and creating an .htaccess
file in the next steps.
.htaccess
File>Enabling an .htaccess
File
#
If you have access to the server settings you can edit the Apache configuration to allow the .htaccess
file to override standard website configurations.
Begin by opening the apache2/sites-available/your_domain.conf
virtual host file with your preferred text editor. Here, we’ll use nano
:
sudo nano /etc/apache2/sites-available/your_domain.conf
Assuming you followed Step 5 of the prerequisite Apache installation guide, this file will contain the following contents:
/etc/apache2/sites-available/your_domain.conf
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName your_domain
ServerAlias www.your_domain
DocumentRoot /var/www/your_domain
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Add the following Directory
content block within the VirtualHost
block:
/etc/apache2/sites-available/your_domain.conf
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName your_domain
ServerAlias www.your_domain
DocumentRoot /var/www/your_domain
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory /var/www/your_domain>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>
The most important line of this Directory
content block is the AllowOverride All
, which enables the use of .htaccess
files. After you’ve added this information, save and close the file. If you’re using nano
you can do this by pressing CTRL + X
then Y
and ENTER
.
Next, restart Apache:
sudo service apache2 restart
Now that your configuration settings have been updated to allow for the use of .htaccess
files, in the next step you will create one.
.htaccess
File>Creating the .htaccess
File
#
To create an .htaccess
file in your terminal, you need to navigate to your web root directory. Your web root directory is where to place the .htaccess
file so that your configurations can be properly executed for your website. The .htaccess
file’s proper placement is important since configurations in that file affect everything in its directory and the directories after it. This means that if you’re serving a couple of different websites on the same Apache server, your .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
.To create an .htaccess
file for your website, run the following command:
sudo nano /var/www/your_domain/.htaccess
Now that you’ve learned a couple of ways to create an .htaccess
file, next we’ll review some common uses of an .htaccess
page.
.htaccess
Page>Common Uses for an .htaccess
Page
#
There are five common uses for an .htaccess
page on your site:
Mod_Rewrite #
One of the most useful facets of the .htaccess
file is mod_rewrite
. You can use the .htaccess
file to designate and alter how URLs and web pages on your sites are displayed to your users. Learn more about how you can do this with our tutorial on How To Set Up mod_rewrite
.
Authentication #
To set up security authentication with .htaccess
, you can create a password file called .htpasswd
to authenticate users. Making this change will create a password portal that prompts site visitors to enter a password if they want to access certain sections of the webpage. When creating this file, make sure to store it somewhere other than the web directory for security reasons.
To create the file, run the htpasswd
command and include the -c
option, and the username to create the specified htpasswd
file. Once this happens, a prompt will ask you to provide a password. You can insert as many lines as needed into the htpasswd
file, but be sure that every user gets their own respective line. The following example illustrates how to create a new entry in the file, in this case for the user sammy:
sudo htpasswd -c /etc/apache2/.htpasswd sammy
You can check the contents of this file by running cat /etc/apache2/.htpasswd
, and it will output the username and encrypted password for each record you added.
Once you’ve added your desired user(s), next open up the .htaccess
file. If you followed the prerequisites guide, this will be located in the following location:
sudo nano /var/www/your_domain/.htaccess
Keep in mind that in this example we’re restricting the entire document root based on /var/www/your_domain
, but this can be placed in any directory to which you want to restrict access.
Once this file is open, add the following contents and save the changes to begin using the password function:
/var/www/your_domain/.htaccess
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
To learn more, read our tutorial on How To Set Up Password Authentication with Apache.
Custom Error Pages #
An .htaccess
file additionally allows you to create custom error pages for your site. Some of the most common errors are:
400 Bad Request
401 Authorization Required
403 Forbidden Page
404 File not Found
500 Internal Error
To make a page user-friendly and provide more information to the site visitor than the default server error page offers, you can use the .htaccess
file to create custom error pages. Read more in our tutorial on How to Configure Apache to Use Custom Error Pages.
MIME Types #
In cases where your site features some application files that your server was not set up to deliver, you can add Multipurpose Internet Mail Extensions (MIME) types to your Apache server in the .htaccess
file with the following code:
/var/www/your_domain/.htaccess
AddType audio/mp4a-latm .m4a
Be sure to replace the application and file extension with the MIME type that you want to support. For this example, we specified an audio file MIME type.
SSI #
Server side includes (SSI) are a great time-saver on a website. One of the most common uses of SSI is to update a large number of pages with some specific data without having to update each page individually. For example, if you want to change a quotation at the bottom of a page.
To enable SSI, insert the following code into your .htaccess
file:
/var/www/your_domain/.htaccess
AddType text/html .shtml
AddHandler server-parsed .shtml</pre>
These lines tell the .htaccess
that .shtml
files are valid, with the second line specifically making the server parse all files ending in .shtml
for any SSI commands.
However, if you have many .html
pages that you are not eager to rename with .shtml
extensions, you can use another tactic to parse them for SSI commands, the XBitHack
.
You can use this XBitHack
tactic by adding the following line to the .htaccess
file to make Apache check all the .html
files with the appropriate permissions for SSI:
/var/www/your_domain/.htaccess
XBitHack on
To make a page eligible for the XBitHack
, use the chmod
command to change permissions:
chmod +x pagename.html
Now that you have an understanding of a few common uses for an .htaccess
page, next you will learn more about the impact an .htaccess
file has on speed and security.
.htaccess
Files>Speed and Security with .htaccess
Files
#
Even though an .htaccess
file can be used to improve a site, there are two things to be aware of that it can influence: speed and security.
Regarding speed, the .htaccess
file may slow down your server, but for most servers, this will probably be an imperceptible change. This could be because of the location of the page since the .htaccess
file affects the pages in its directory and all of the directories after it. This means that each time a page loads, the server scans its directory, and any directories preceding it until it reaches the highest directory or an .htaccess
file. This process will occur as long as the AllowOverride
directive allows the use of .htaccess
files as was demonstrated in the enabling an .htaccess
file step; whether or not the .htaccess
files actually exist.
For security, the .htaccess
file is much more accessible than standard Apache configuration and the changes are made live instantly (without the need to restart the server). This grants users permission to make alterations in the .htaccess
file, giving them a lot of control over the server itself. Any directive placed in the .htaccess
file, has the same effect as it would in the Apache configuration itself. It’s also important to note that Apache generally discourages the use of .htaccess
if the user can access the Apache configuration files themselves.
Conclusion #
The .htaccess
file gives you a lot of flexibility to build up your site. To learn more about securing your site, read our tutorial on setting up password authentication with Apache. You can also read more in our tutorial about installing an Apache web server and specifically important Apache Files and Directories.