Logo

How to Enable and Set Up .htaccess on Apache

Try this guide with our instant dedicated server for as low as 40 Euros

Apache is one of the most popular, open, and cross-platform web servers on the Internet. Whether you are a developer or sysadmin, it is very probable that you have worked with Apache as your web or application server. 

Apache has a reputation for being very configurable and can accommodate a range of scenarios for hosting and managing web apps. 

This capability comes from the .htaccess file, a powerful configuration tool that allows users to control and customize various aspects of a website’s behavior on an Apache web server. 

Users can manage several server configuration capabilities, such as URL rewrites and directory-level permissions, through the .htaccess file. 

In this tutorial, we will discuss how to enable the .htaccess file and a few use cases of using the file for configuring IP addresses and redirection.

Let’s start with an overview of the file. 

Table Of Contents

  1. What is Apache .htaccess File
    1. The Capabilities of .htaccess File
  2. How to Enable and Set Up .htaccess on Apache
    1. Step #1: Open the Configuration File
    2. Step #2: Modify AllowOverride
    3. Step #3: Save and Restart
  3. Set Up .htaccess File on Apache
    1. Step #1: Create the File
    2. Step #2: Restrict Directory Listings
    3. Step #3: Modify the File
  4. Managing IP Addresses
    1. Allow Specific IP Addresses
    2. Block Specific IP Addresses
    3. Block Visitors by Referrer
  5. Traffic Redirection and Custom Error Pages with .htaccess
    1. Traffic Redirection
    2. Set a Custom 404 Page
  6. Conclusion
  7. FAQs

What is Apache .htaccess File

An Apache .htaccess file is a special configuration file used on Apache web servers. It allows website owners to make changes to how their website behaves in specific situations without modifying the main server configuration.

The Capabilities of .htaccess File

The .htaccess file, also known as distributed configuration file, lets the owners control several aspects. These include:

  • Password Protection: Restricts access to specific areas by requiring a login/credentials.
  • URL Rewriting: Create simple and more user-friendly URLs for your website.
  • Custom Error Pages: Display informative error messages instead of generic server errors.
  • MIME Types: Define how the server handles different file formats (images, videos, etc.).

While the .htaccess file is a powerful tool, configuring it requires immense caution, as a simple mistake can compromise the server’s security and performance. Also, note that extensive use of .htaccess can slightly slow down the server. We recommend prioritizing changes in the main configuration for better efficiency.

Let us now take a quick look at the prerequisites for working with the .htaccess file

The Prerequisites

Before diving into the setup, ensure you have the following:

  • An Apache web server
  • A user account with root or sudo privileges
  • A text editor like Nano or Vim
  • Access to the terminal/command line.

How to Enable and Set Up .htaccess on Apache

Now that you have a basic understanding of the .htaccess file on Apache, let us discuss how to enable and set up the .htaccess file.

In most cases, the .htaccess file is not enabled by default. Therefore, the first step is to enable the .htaccess file. The steps of the process are as follows:.

Step #1: Open the Configuration File

Open the default host configuration file in your preferred editor. We will open it in Nano by executing the following command:

# sudo nano /etc/apache2/sites-available/default

Step #2: Modify AllowOverride

Navigate to the section <Directory /var/www>

This section defines configurations for your website’s document root directory (usually /var/www).

Next, modify the line AllowOverride None to AllowOverride All

This enables .htaccess functionality for this directory.

Modify Allow Override

Step #3: Save and Restart

Press Ctrl+O to save the changes and exit the editor with Ctrl+X.

Once you exit the editor, restart the Apache service to apply the changes. 

# sudo service apache2 restart

Now that you have successfully enabled the .htaccess file, let us understand how to set up the .htaccess file on Apache.

Set Up .htaccess File on Apache

Apache depends on configuration files, much like most Linux software software. One of these is the .htaccess file. This file uses a system of variables and values to direct the various server operations. 

We recommend the following steps to set up a .htaccess file on Apache:

Step #1: Create the File

Execute the following command that uses Nano to create and open the .htaccess file in the desired directory: 

# sudo nano /var/www/my_website.com/.htaccess

Replace my_website.com with your actual website directory. 

Step #2: Restrict Directory Listings 

Next, once you have created and opened the .htaccess file, it is necessary to restrict directory listings and enhance security. 

Therefore, create a new file .htpasswd in a secure directory. This file stores the usernames and encrypted passwords of authorized users.

# sudo nano user//safe_location/.htpasswd

Replace /user/safe_location/ with your preferred secure location. Do not store this file within your web directory to avoid potential security risks.

Add usernames and passwords for every user you want to create in the following format. Remember that you should add one entry per line.

username:encrypted_password

Once you have added all the usernames and passwords, save and exit the file. 

Step #3: Modify the File

Next, modify the .htaccess file to enable basic authentication using the .htpasswd file you just created. For this, add the following lines to your .htaccess file:

AuthUserFile /user/safe_location/.htpasswd

AuthGroupFile /dev/null

AuthName "Please Enter Password"

AuthType Basic

Require valid-user

Modify the File

Replace /user/safe_location/.htpasswd with the actual path to your .htpasswd file.

Here, 

  • AuthUserFile: This configures your .htpasswd file’s location.
  • AuthGroupFile: This is a placeholder since group authentication isn’t used.
  • AuthName: This is displayed when users are prompted to enter the password. 
  • AuthType: Specifies the authentication type.

Managing IP Addresses

While .htaccess doesn’t directly manage IP addresses, it can be used alongside other IP restriction mechanisms for stronger security. Some of the common IP management methods are as follows:

Allow Specific IP Addresses

You can use .htaccess to manage IP addresses is a practical way to control access to your website and enhance its security. 

Add the following lines to the .htaccess file to grant access to specific IP addresses:

order deny, allow

allow from [ IP_address]

allow from [ IP_Address]

Replace [IP_Address_1] and [IP_Address_2] with the actual IP addresses you want to allow. This configuration only allows access to the specified IP addresses.

Block Specific IP Addresses

Alternatively, you can add specific IP addresses that the system should deny access to the website. For this, add the following lines to the file: 

Order allow,deny

Deny from [IP_Address_To_Block]

Replace [IP_Address_To_Block] with the IP address you want to deny.

If you wish to block a range of IP addresses from accessing the website, omit the last octet. This will block all IP addresses within that range.

For instance, to block IP addresses in the range of 0 to 255, add the following line to the file:

deny from 10.10.0.11.

Note: We strongly recommend caution when blocking entire IP ranges because this can unintentionally block legitimate traffic. IP-based restrictions might not be foolproof, so consider additional security measures like strong passwords.

Block Visitors by Referrer 

There are scenarios where you might want to restrict traffic coming from specific websites (referrers) to your website. This is a critical security precaution that blocks traffic from suspicious traffic sources. 

You can follow these steps to block visitors by referrer:

Open the .htaccess file and add the following statement block:

RewriteEngine on

# Options +FollowSymlinks

RewriteCond %{HTTP_REFERER} blockeddomain\.com [NC]

RewriteRule .* - [F]

Replace blockeddomain.com with the actual domain name of the referrer you want to block.

Here, 

The NC flag ensures the rule is case-insensitive. 

You can expand this rule and block visitors from multiple websites by adding the OR flag and the following additional conditions:

RewriteEngine on

# Options +FollowSymlinks

RewriteCond %{HTTP_REFERER} blockeddomain\.com [NC,OR]

RewriteCond %{HTTP_REFERER} blockeddomain2\.com

RewriteRule .* - [F]

Add additional RewriteCond lines with the referrers you want to block.

Next, save your changes to the .htaccess file and restart your Apache web server for the modifications to take effect.

Traffic Redirection and Custom Error Pages with .htaccess

The .htaccess file on Apache offers functionalities beyond access control. You can use it to manage traffic and redirect the users to specific error pages.

Traffic Redirection

Redirecting traffic from one URL to another is necessary when you have to move content to a new location permanently (301 redirects) or when temporarily redirecting traffic during maintenance (302 redirects).

Follow these steps to redirect the traffic to a different URL:

Open the .htaccess file.

Add the following line to the .htaccess file to redirect traffic:

# Redirect301/Other_Website.com/index.html/My_Website.com/index.html

The statement redirects traffic looking for Other_Website.com to My_Website.com.

Save the .htaccess file and restart your Apache web server for the redirection to take effect. 

Set a Custom 404 Page

Apache displays default error messages for various HTTP status codes (e.g., 404 Not Found, 500 Internal Server Error, 502 Bad Gateway). 

You can customize these messages using .htaccess by following these steps:

Open the .htaccess file and add the following ErrorDocument directive.

ErrorDocument 404 /404.html

This line instructs the system to look at the website’s content directory for a /404.html file as the error page.

Next, create the custom error page (Here, the 404 page) using the following command:

# sudo nano cd /var/www/My_Website.com/public.html/404.html

This should open the 404.html file in your text editor.

Next, add the following code to the file:

<!doctype html>

<html>

 <body>

  404 Error: Page not found

 </body&gt;

</html>

You can now configure this page to display any kind of error message. You can also customize any other error pages. 

The .htaccess file is of critical importance in WordPress operations. We recommend our tutorial on using the .htaccess file in WordPress for controlling and enhancing the user experience. 

Conclusion

Enabling .htaccess functionality on your Apache web server unlocks a range of customization options. 

By following the steps provided in the guide, you can prioritize security and leverage .htaccess to enhance your website’s functionality, user experience, and overall management while maintaining the control and flexibility offered by Apache.

FAQs

Q. What is .htaccess?

Apache web servers use the .htaccess file as a configuration file to adjust directory-level configurations, including redirects, access control, and URL rewriting.

Q. How do I enable .htaccess on Apache?

Open the default host configuration file by executing # sudo nano /etc/apache2/sites-available/default. Modify the line AllowOverride None to AllowOverride All in the <Directory /var/www> section

Q. How do I create or edit the .htaccess file?

You can update an existing .htaccess file or create a new one using a text editor. Add the configurations you want by using the relevant Apache directives.

Q. Where should I place the .htaccess file type?

The .htaccess file type should be placed in the root directory of your website or in the particular directory where you want the configurations to take effect.

Q. How do I test my .htaccess configurations?

Once the .htaccess file has been saved and uploaded, check that your setups work as they should. Look for any mistakes or strange conduct.

Q. Are there security considerations for .htaccess?

Ensure that your .htaccess file type and configurations adhere to best security practices. Avoid including sensitive information and regularly review and update access controls.

Q. What kind of configurations can I add to .htaccess?

Using appropriate Apache directives, you can add various configurations, including URL rewriting, access control, password protection, redirects, MIME types, and more.

Q. How does .htaccess customization enhance website functionality?

Customizing .htaccess allows you to tailor Apache server settings to your needs, improving website functionality, performance, and user experience.

Try this guide with our instant dedicated server for as low as 40 Euros