How to Setup & Enable htaccess on Apache {With Examples} (2024)

Introduction

The .htaccess file in Apache allows configurations at the directory and subdirectory level. Using .htaccess enablesyou to configure website permissions without altering server configuration files.

This tutorial will show how to set up and enable .htaccess on Apache, restrict access to specific localizations on the server, manage IP addresses, and more.

How to Setup & Enable htaccess on Apache {With Examples} (1)

Prerequisites

  • A working Apache web server installation (this guide uses an Ubuntu Apache installation).
  • Access to a terminal window/command line.
  • Access to a user account with root privileges.
  • A text editor, such asnano.

How to Enable .htaccess in Apache

By default, the .htaccess file is not enabled primarily for security and performance reasons. Allowing .htaccess files can introduce security vulnerabilities if users misconfigure the settings to expose sensitive information or weaken server security. Additionally, improperly configuring the server can significantly degrade performance.

The sections below show how to enable .htaccess in Apache and configure it properly.

Note: Check out our detailed comparison article and learn the difference between Apache and Nginx, two top web server utilities.

Step 1: Enable .htaccess

Follow the steps below to enable .htaccess in Apache:

1. Open the default host configuration file by running the following command:

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

2. Locate the section labeled <Directory /var/www>. In that section, change the AllowOverride None entry to:

AllowOverride All
How to Setup & Enable htaccess on Apache {With Examples} (2)

3. Save the file and exit.

4. Restart the Apache service for the changes to take effect:

sudo systemctl apache2 restart

Step 2: Create .htaccess File

Like most Linux software packages, Apache functions on configuration files, one of which is the .htaccess file. It works by specifying a setting along with a value. If your server does not have an .htaccess file, it might be configured globally or might not require one.

However, if you need specific directory-level configurations or URL rewrites, you can create and manage .htaccess files as needed. Follow the steps below:

1. Create and open the .htaccess file for editing with the following command:

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

Replace my_website.com with the name of your actual website.

2. Save the file and exit.

3. Restart the Apache service to apply the changes:

sudo systemctl apache2 restart

Step 3: Restrict Directory Listings

There may be locations on your server that you want to restrict access to. You can do this by creating a list of usernames and passwords that are authorized to have access.

1. Start by creating a new file - .htpasswd, in a separate directory:

sudo nano /user/safe_location/.htpasswd

2. In the file, enter a username and password for each user that you want to create. Make sure to use strong passwords and enter only one username/password pair per line.

Tip: Try our free password generator.

3. Save the file and exit.

4. Next, edit .htaccess and paste the following lines to enable authentication:

AuthUserFile /user/safe_location/.htpasswdAuthGroupFile /dev/nullAuthName "Please Enter Password"AuthType BasicRequire valid-user
How to Setup & Enable htaccess on Apache {With Examples} (3)
  • Replace/user/safe_location/.htpasswdwith the location of your choice. Don't store it in the same directory as your web content, for security reasons.
  • AuthUserFile. Sets the location for your .htpasswd file.
  • AuthGroupFile. If you are not using a group, keep this as a placeholder.
  • AuthName. The text displayed to the user. You can phrase it as you like.
  • AuthType. Type of authentication used - keep the default value.
  • Require valid-user. Allows any of the several authorized people to log on. You can change this to Require user new_user to restrict access only to someone with the username new_user.

Why Configure an Apache .htaccess File and How?

Configuring an Apache .htaccess file allows you to manage server settings such as redirects, access control, and URL rewriting on a per-directory basis without modifying the main server configuration. It is also important to configure the file properly to prevent unauthorized access.

This section shows the most common configuration settings and how to set them properly.

Custom Error Pages

You can use the .htaccess file to point basic functions to a new location, such as custom error pages. One example is the 404 page. Follow the steps below:

1. Open the .htaccess file and paste the following line:

ErrorDocument404 /404.html

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

2. Create the 404 page using the command below:

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

Replace My_Website.com with your website address.

The command will open the 404.html file in your text editor.

3. Paste the following code in the file:

<!doctype html><html><body> 404 Error: Page not found</body&gt;</html>
How to Setup & Enable htaccess on Apache {With Examples} (4)

You can customize this page to display anykind of error message. You can also customize any other error pages you want. Just specify theErrorDocument number,for example, Error 500, and then point .htaccess to the new error.html file that you create.

Redirections

Redirections are essential for directing traffic from outdated URLs to new ones, managing moved content, or consolidating multiple URLs into a single destination. You can use the .htaccess file to create both temporary (302) and permanent (301) redirects.

For example:

Open the .htaccess file and paste the following:

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

This line instructs Apache to take any traffic searching for Other_Website.com and redirect it to My_Website.com. Replace the values with your own website addresses.

Blocking Traffic

Blocking unwanted traffic, such as malicious bots or users from specific IP addresses, can be efficiently handled with .htaccess. It is possible to:

  • Allow only specific IPs.
  • Block specific IP addresses.
  • Block visitors by the referrer.

The sections below explain each scenario.

Allow Specific IP Addresses

To allow access to specific IP addresses only, specify them in the .htaccess file. Open the .htaccess file and paste the following lines:

order deny, allow allow from 192.168.0.54allow from 192.168.0 
How to Setup & Enable htaccess on Apache {With Examples} (5)

The lines above allow access only to the specified IP addresses and block the rest.

Block IP Addresses

Depending on whether you want to block a single or a range of IP addresses, use one of the following:

  • To block a single IP address, use the following syntax:
deny from 192.168.1.1
  • Block multiple IP addresses:
deny from 192.168.1.1 192.168.1.2 192.168.1.3
  • Block a range of IP addresses:
deny from 192.168.1.0/24

If you leave off the final digit, it will block all IP addresses in the 0 - 255 range. For example:

deny from 192.168.0

Note: You can save your .htaccess file after each operation listed above. When you finish making changes, just reload your Apache service before testing. It is also helpful to add comments to the file. Use the # sign to mark a line as a comment, which will let you make notes that the system won't read as commands.

Cross-Origin Resource Control

Cross-Origin Resource Sharing (CORS) restricts web pages or scripts from accessing resources from another domain. To manage cross-origin requests and improve security, .htaccess can set CORS headers to control which domains are allowed to access resources on your server.

The following is an example configuration of the .htaccess file that defines who can access resources and which methods are permissible, preventing unauthorized cross-origin requests:

# Allow all domainsHeader set Access-Control-Allow-Origin "*"# Allow a specific domainHeader set Access-Control-Allow-Origin "https://example.com"# Allow multiple methodsHeader set Access-Control-Allow-Methods "GET, POST, PUT"

mod_rewrite

The mod_rewrite module provides a flexible and powerful way to manipulate URLs using rules defined in .htaccess. It is commonly used for creating user-friendly URLs, redirecting traffic, and rewriting request URLs.

The following example configuration enables mod_rewrite, redirects non-www URLs to their www counterparts, and rewrites requests from product/123 to product.php?id=123:

# Enable mod_rewriteRewriteEngine On# Redirect non-www to wwwRewriteCond %{HTTP_HOST} ^example\.com [NC]RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]# Rewrite URLs to a single scriptRewriteRule ^product/([0-9]+)$ /product.php?id=$1 [L]

You can also use mod_rewrite to prevent people from being redirected from a specific site to your server. This might be helpful if you want to isolate traffic patterns. You can also use it if you are getting excess server traffic from a questionable source.

Open the .htaccess file and add the following block:

RewriteEngine on# Options +FollowSymlinksRewriteCond %{HTTP_REFERER} blockeddomain\.com [NC]RewriteRule .* - [F]

The NC option instructs to ignore the upper or lower case so that the rule cannot be bypassed by entering BlockedDomain.com.

If you want to add more domains, note the following:

RewriteEngine on# Options +FollowSymlinksRewriteCond %{HTTP_REFERER} blockeddomain\.com [NC,OR]RewriteCond %{HTTP_REFERER} blockeddomain2\.comRewriteRule .* - [F]

The OR flag tells the system that you are not done adding blocked referrers yet. Omit this option on the last entry.

CGI Execution

The Common Gateway Interface (CGI) allows a web server to interact with external content-generating programs, such as CGI programs or CGI scripts. CGI allows you to place dynamic content on your website in any programming language you are most familiar with. The .htaccess file can be used to enable or configure CGI script execution in a directory.

Open the .htaccess file and add the following lines to enable CGI execution and specify the script handler:

<Directory "/home/*/public_html"> Options +ExecCGI AddHandler cgi-script .cgi .pl</Directory>

The configuration above allows CGI program execution for any file ending in.cgi and .plin users' directories.

Server-Side Includes (SSIs)

Server Side Includes (SSIs) allow HTML pages to include other files or script outputs, facilitating a modular and maintainable web page design. You can enable SSIs via .htaccess.

Open the .htaccess file and paste the following code to enable SSIs:

AddType text/html .shtmlAddHandler server-parsed .shtmlOptions Indexes FollowSymLinks IncludesAddHandler server-parsed .html .htm

This configuration tells Apache to treat .shtml, .html, and .htm files as HTML and allows them to be parsed for Server-Side Includes (SSI). It also enables directory listings, symbolic link following, and server-side includes.

Conclusion

Enabling .htaccess can be an incredibly valuable tool for managing your Apache web server. It provides granular control over web server configurations on a per-directory basis, making it ideal for implementing specific rules and settings without modifying the global server configuration.

This guide provided the basic commands and configurations for .htaccess, with some of the most likely scenarios you might encounter.

Next, learn how to fix the Apache 403 Forbidden error or see how to set up Apache Virtual Hosts on Ubuntu.

How to Setup & Enable htaccess on Apache {With Examples} (2024)
Top Articles
Latest Posts
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 5551

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.