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)

FAQs

How do I enable .htaccess in Apache? ›

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.
Jul 1, 2022

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.

Where to place .htaccess file in Apache? ›

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 /.

Do you need to restart Apache for htaccess? ›

No, you will not need to restart Apache. You will need to "hard refresh" your web page to see the changes. Simply browse your site and go to the page that should be affected.

What is the purpose of .htaccess file in Apache? ›

htaccess files allow users to configure directories of the web server they control without modifying the main configuration file. While this is useful it's important to note that using . htaccess files slows down Apache, so, if you have access to the main server configuration file (which is usually called httpd.

How to create a .htaccess file? ›

htaccess file in the root directory, go to the WordPress dashboard > Settings > Permalinks, and click on Save Changes to create a new . htaccess file.

Why is my .htaccess file not working? ›

The filename is misspelled or does not begin with a period

htaccess file included) then you must ensure that the filename is correct and that it begins with a period ( . ). Without the period at the beginning, Apache will ignore the file - the same goes for if the file is misspelled.

Where is the .htaccess file on my server? ›

Navigate to your website's root folder, typically called public_html, www, or your website name. Here, you'll find the . htaccess file. If you don't see that file, you may need to turn on a setting that enables you to view hidden files.

How do I check my htaccess file? ›

Where is my . htaccess file?
  1. Login to your cPanel.
  2. Under the Files section, click on File Manager.
  3. Locate your . htaccess file, you may have to show hidden files.
Nov 27, 2023

What should a .htaccess file contain? ›

. 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.

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 do I disable a .htaccess file? ›

Disable your . htaccess file
  1. Connect to your hosting account with FTP.
  2. Once connected, go to the root directory for your WordPress site, which is the folder containing your site.
  3. Locate the . htaccess file and rename it to . htaccess. disabled. Renaming the . htaccess prevents it from affecting your site.

How to access files on Apache server? ›

How to Access the Apache Configuration Files on Your web Server
  1. Log in to your website with the root user via a terminal and navigate to the configuration files in the folder located at /etc/httpd/ by typing cd /etc/httpd/. ...
  2. Press the Insert key to begin editing the file.

Does restarting Apache clear cache? ›

flush. A restart of Apache should flush the cache.

What does restarting Apache do? ›

Restart Now

It re-reads its configuration files, and re-opens any log files. Then it spawns a new set of children and continues serving hits. Users of mod_status will notice that the server statistics are set to zero when a HUP is sent. As with a graceful restart, a syntax check is run before the restart is attempted.

How do I make sure Mod_rewrite is enabled in Apache? ›

Enabling Apache Mod_Rewrite
  1. #1 Install Apache HTTP Server. Make sure you have Apache installed on your server. ...
  2. #2 Enable mod_rewrite Module. ...
  3. #3 Update Apache Configuration. ...
  4. #4 Restart Apache. ...
  5. #5 Set Up . ...
  6. #6 Write Rewrite Rules. ...
  7. #7 Test Your Rewrite Rules.
Aug 11, 2023

How do I enable logging in Apache? ›

Configuration
  1. Open /etc/apache2/apache2.conf and add a new log format line: LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\" %{X-Forwarded-For}i %I" ui-format. ...
  2. Once defined in apache2. ...
  3. Restart Apache web server.
Mar 23, 2021

How do I enable redirect in Apache? ›

You can create a temporary redirect in Apache by adding a line like this to the virtual host entry in the server configuration file:
  1. Redirect /oldlocation http://www.newdomain.com/newlocation.
  2. Redirect permanent /oldlocation http://www.newdomain.com/newlocation.
Dec 14, 2016

How do I enable Apache status? ›

To access the Apache Server Status page, you need to enable it in the Apache configuration file, usually located in httpd. conf . Once enabled, you can view the status page by navigating to http://yourserver.com/server-status . Remember to replace yourserver.com with your server's actual domain name.

Top Articles
Weekly BBQ Specials | Famous Dave's BBQ
Dine-In & To Go Menu | Famous Dave's BBQ | Chicago
Capital In The Caribbean Nyt
Barstool Sports Gif
5daysON | Hoofddorp (70089000)
Dr Frita Mcrae Fisher Husband
Choke Pony Dating App
Ups Cc Center
80 For Brady Showtimes Near Brenden Theatres Kingman 4
What Is Opm1 Treas 310 Deposit
How To Get To Brazil In Slap Battles
Craigslist Tuscarawas Pets
Einfaches Spiel programmieren: Schritt-für-Schritt Anleitung für Scratch
Varsity Competition Results 2022
What retirement account is tax-free?
Wmlink/Sspr
Nsu Occupational Therapy Prerequisites
Emily Katherine Correro
Nbl Virals Series
Summoner Weapons Terraria
Dmv Rocklin Wait Times
159R Bus Schedule Pdf
Best Fantime Accounts
O'reilly's Eastman Georgia
What Does Exp Wed Mean On Hulu
Account Now Login In
Streameast Io Soccer
10 Best-Performing Bi-Directional Scan Tools in 2023 (Full Control)
Los Garroberros Menu
2005 Chevy Colorado 3.5 Head Bolt Torque Specs
Fingerhut Teleflora Promo Code
A Closer Look at Ot Megan Age: From TikTok Star to Media Sensation
Craigs List Skagit County
Petco Clinic Hours
How To Get Stone Can In Merge Mansion 2022
Stephen King's The Boogeyman Movie: Release Date, Trailer And Other Things We Know About The Upcoming Adaptation
Get Over It Stables
Let's Take a Look Inside the 2024 Hyundai Elantra - Kelley Blue Book
Bbc Weather In Mallorca
What Does It Mean When Hulu Says Exp
Kelly Chapman Husband
Ihop Ralph Ave
Craigslist Hawley Pa
Mama Mia Israel Soldier Original
Hyundai Elantra - modele, dane, silniki, testy
Oppenheimer Showtimes Near B&B Theatres Liberty Cinema 12
Empire Of Light Showtimes Near Santikos Entertainment Palladium
Schematic Calamity
Obsidian Guard's Skullsplitter
LP Vinyl Samling pop rock thrash metal trance
What stores are open on Labor Day 2024? A full list of where to shop
Unblocked Games 76 Bitlife
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 5644

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.