A .htaccess file or a distributed configuration file is a robust file used to control and manage the configurations of a website. All the configuration changes are made on a per-directory basis to ensure that the main server configuration files are undisturbed.
When to Use .htaccess File Preferred
Whether you aim to load error pages or implement password security, a .htaccess has a list of uses. Some of the most common examples include:
-
Adding redirections for a specific URL or a list of URLs.
-
Enabling password protection on certain directories on a server.
-
Loading customized error pages.
-
Reinforcing a site to use HTTPS instead of HTTP.
-
Blocking targeted IPs or domains.
In this guide, we will walk you through the steps to enable, create and use the .htaccess file.
Prerequisites
To follow this tutorial, you must have the following:
-
The latest version of Ubuntu is installed on your system.
-
Apache web server must be installed on your Ubuntu server.
-
Apache virtual host set up for your domain.
-
System users must have sudo privileges.
-
Secured virtual host with SSL.
-
Follow Securing Apache with Let’s Encrypt on Ubuntu 18.04 if you configure and secure Apache using your customized domain.
-
Alternatively, you can Create a Self-Signed SSL Certificate for Apache in Ubuntu 20.04 if you intend to use Apache for testing needs.
-
Note: There are a lot of domain providers you can consider buying customized domains online. Namecheap, Freenom, and Bluehost, to name a few, are well known for their exceptional service. |
Once you’re done with the initial setup, log into your server as the sudo user, and let’s start.
Step 1 — Enable the .htaccess File
By default, the .htaccess file is disabled. We need to first change the Apache configuration and enable the .htaccess file.
Open the apache2/sites-available/your_domain.conf virtual host file using nano or any preferred text editor:
1 |
$ sudo nano /etc/apache2/sites-available/your_domain.conf |
Assuming you are ready with the set up discussed in the Apache web server guide, you will find the following configuration detail:
1 2 3 4 5 6 7 8 |
<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> |
Next, include the following Directory content within the VirtualHost block:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<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> |
In the above code block, the line AllowOverride All under the Directory section is the most significant of all. This section enables the use of .htaccess files.
After that, save your work and close the file. If you’re using the nano text editor, use the shortcut CTRL + X, Y, and ENTER to close the file.
Check the configuration before you restart the web server:
1 |
$ sudo apache2ctl configtest |
You’ll see Syntax OK as output if everything is in place. Now, restart the server to add your password policy:
1 |
$ sudo systemctl restart apache2 |
Once the .htaccess file settings are enabled, it’s time to create a new file.
Step 2 — Create a .htaccess File
Creating a .htaccess file is straightforward. You have to navigate to the web root directory i.e. the source to locate the .htaccess file to ensure that the configuration changes are rightly executed.
Note: Be cautious when locating the .htaccess file. A subtle error in the configuration might adversely affect its directory and its following directories. For instance, if you aim for multiple websites on the same Apache server, place your .htaccess file in the web root directory mapped with the website. |
If you have followed the prerequisite discussed above, you will get the web root directory at /var/www/my_domain/.htaccess. Next, create a .htaccess file for your website using:
1 |
$ sudo nano /var/www/your_domain/.htaccess |
Once we have our .htaccess file ready, let’s check out some of its use cases.
Step 3 — Common Uses of .htaccess File
Using a .htaccess page on your site comes with a list of advantages. Let’s discuss each in detail:
-
Redirecting URLs
URL Redirecting also referred to as URL forwarding, is a web server function used to redirect a domain’s visitor to another URL. You can use .htaccess for your URL redirecting needs. Add the following in your .htaccess file to map the source URL to the targeted URL:
1 2 3 4 |
RewriteEngine on RewriteCond %{HTTP_HOST} ^testdomain.com [NC,OR] RewriteCond %{HTTP_HOST} ^www.testdomain.com [NC] RewriteRule ^(.*)$ http://demodomain.com/$1 [L,R=301,NC] |
-
Create Custom Error Pages
A useful facet of the .htaccess file is to create a custom error page. Generally, when a user encounters a page that doesn’t exist on the website, an error message pops up on the screen. Some of the common HTTP error codes include:
-
400 Bad Request
-
401 Unauthorization
-
403 Forbidden
-
404 Not Found
-
500 Internal Server Error
-
502 Bad Gateway
-
503 Service Unavailable
Unlike the default server page error “Page Not Found”, make use of the .htaccess file to provide your users with an enhanced, user-friendly browsing experience.
-
Set Up Security Authentication
Using the .htaccess file, you can also set up security authentication. For this, you need to create a .htpasswd file to authenticate users.
Use the htpasswd command to create a password file for security purposes. Apache will use this password file to authenticate verified users. Navigate to the /etc/apache2 directory and create a confidential file called .htpasswd.
To create the necessary .htpasswd file, use the -c option the first time you use this password security utility. Next, specify the username at the end of the command to list a new entry within the file. After that, replace the username nick (used in this tutorial) with your username:
1 |
$ sudo htpasswd -c /etc/apache2/.htpasswd nick |
Next, you will be asked to provide and verify the user’s password.
Continue reading this tutorial to learn more about setting up and configuring password authentication with Apache on Ubuntu 20.04.
-
Add MIME Types
Classification of files used on the Internet is effortless using Multi-Purpose Internet Mail Extensions (MIME) type. In several scenarios where a website fails to deliver a specific file, adding extensions does the job. Use the following code to add Multipurpose Internet Mail Extensions (MIME) types to your Apache server in the .htaccess file:
1 |
AddType audio/mp4a-latm .m4a |
Note: In our guide, we have an audio file MIME type. Replace the application and file extension with your targeted MIME type. Additionally, ensure that the virtual host configuration and the .htaccess file’s location directory are able to use the AddType directive. Otherwise, you will get a 500 Internal Server Error. |
-
Server Side Includes(SSI)
SSIs are directives that feed dynamic content to an HTML page. It is used for updating a large number of pages with some specific data without the need to update each page explicitly.
In the HTML files, the Server Side Includes SSI is disabled by default. Add the following code to your .htaccess file to enable SSI:
1 2 |
AddType text/html .shtml AddHandler server-parsed .shtml</pre> |
The above lines first validate the .shtml files. The confirmation is then sent to the .htaccess file whilst allowing the server to parse all .shtml files.
Alternatively, you can use the XBitHack to parse multiple .html contents instead of renaming the .shtml extensions one by one. Add the following line to the .htaccess file to use XbitHAck and request Apache to check all the .html files:
1 |
XBitHack on |
Next, you need to change permission to pass the page eligibility to use XBitHack. Use the following chmod command to do this:
1 |
$ chmod +x pagename.html |
-
Manage IP address
Sometimes, you may aim to block an IP or a range of IP addresses visiting your site for security purposes. Insert the following lines of code into your .htaccess file to restrict the targeted IP:
1 |
Order Deny, Allow Deny from A.A.A.A (where A.A.A.A is a specific IPv4 Address) |
Use a separate line for blocking more than one IP:
1 |
Order Deny Allow Deny from A.A.A.A (where A.A.A.A is a specific IPv4 Address) Deny from B.B.B.B (where B.B.B.B is a specific IPv4 Address) |
Besides, you can block domains from accessing your website. Restrict a specific domain by adding the following line of code to the .htaccess file:
Order Deny, Allow Deny from www.blockdomain.com (where www.blockdomain.com is a specific domain)
Red Flags of Using .htaccess
Adding a .htaccess file is undeniably a smart move to configure your website and make it user-friendly. However, any modifications done in the configuration settings come with other costs packed with it. Let’s check some compelling reasons suggesting why you must not use the .htaccess file:
i. Performance Loss: Every time a server scans a page directory and its .htaccess file, the page loads. As a result speed and performance loss becomes a prime concern.
ii. Security: Access to .htaccess files gives full control over server configuration. That means any unauthorized user who gets .htaccess access to the .htaccess file, which in turn leads to potential security risks.
iii. Accessibility: The .htaccess files must be handled with utmost care and attention. If there are any errors in the .htaccess file, it can bring the entire website down.
Conclusion
In this guide, we got a comprehensive idea of enabling, creating, and using a .htaccess file. We discussed the use case when and where the .htaccess file must be used. Leverage .htaccess files to safeguard your website and protect it against attack. However, there are several pitfalls of using this configuration file that must not be ignored. In a nutshell, use the .htaccess files depending upon your server’s usage and user’s access needs.
Furthermore, there are other networking tutorials that you can find on our blog:
-
Configuring Basic HTTP Authentication with Nginx on Ubuntu 20.04
-
Nginx HTTP Proxying, Load Balancing, Buffering, and Caching: an Overview
- How To Enable, Create and Use the .htaccess File: A Tutorial - March 8, 2023
- An Overview of Queries in MySQL - October 28, 2022
- Introduction to Cookies: Understanding and Working with JavaScript Cookies - October 25, 2022
- An Overview of Data Types in Ruby - October 24, 2022
- The Architecture of Iptables and Netfilter - October 10, 2022