What Is the .htaccess File? Your Complete Guide

Reriterule, AllowOverride, Redirects, RewriteEngine

Proper and Common Uses with Examples

Configuration Changes Per Directory or Website Basis

Updated: March 22, 2025
By: RSH Web Editorial Staff

Contact Us

Menu

.htaccess

A file with the .HTACCESS (Hyper Text Access) extension is an Apache Access Configuration File. These are text files used to invoke an exception to the global settings that apply to the various directories of an Apache website. Another common use for this file is for pointing to an .HTPASSWD file that stores credentials preventing visitors from accessing that particular directory of files.

What is an .htaccess File?

The .htaccess file in Apache is a list of commands that allows Server configurations at the directory and subdirectory level. Using this file enables you to configure website permissions without having to altering Server configuration files. You can set 404 error pages, control the server's configuration, modify the default settings, password protect directories, redirects, deny users based on IP and more.

Warning: Because the .htaccess file is a Server Configuration File. A typo can cause your Server to be misconfigured. This can result in the Server or your Website not working. If you are not sure of modifying this file, consult with a web developer. Be sure to make backups of your original .htaccess file and proceed carefully.

Note: If you have access to HTTPD main Server config file, you should avoid using .htaccess files. Using the .htaccess files can slow down your Apache HTTP Server. Any directive that you can include in a .htaccess file is better set in a Directory block, as it will have the same effect with better performance.

Note: If you want to call your .htaccess file something else, you can change the name of the file using the AccessFileName directive. For example, if you would rather call the file .config then you can put the following in your server configuration file:
AccessFileName ".config"

Advantages of Using The .htaccess file

Reads all requests. Because .htaccess files are read on every request. Any changes made in these files take immediate effect. Opposed to the main configuration file, which requires the Server to be restarted for the new settings to take effect. It can effectively manage user access based on the preference. Sets directory level configurations. Can increase SEO efforts.

Location of the .htaccess File

Normally this file in the root folder. If you are not able to find it in the root folder, then it might be hidden. Enable hidden files in the settings of your program. Go to the "public_html" or "WWW" folder. This is where you will find all your website files. A single directory and multiple website subdirectories can have a separate .htaccess file.

.htaccess File Examples - Code Snippets

There are a vast amount of configuration possibilities that can be achieved within the .htaccess file. The list below is a few of the more commonly used examples.

Working with the .htaccess file

You can access, view and edit the .htaccess file through cPanel's File Manger or our preferred method is with a FTP program and a good Text Editor such as Note Pad++. Remember, this file always starts with a period.

Allow All or Deny From - Statement

With this example, it means that any person can access to your website or server
Notice the "allow from all".

<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>


If you wanted to deny a user by way of their IP numbers, it might look like this.

<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
deny from 127.0.0.1
allow from all
</Directory>

Business Hosting

Error Page Redirects

A 404 error is an HTTP status code that means that the web page you were trying to reach could not be found.

ErrorDocument 403 /forbidden.html
ErrorDocument 404 /notfound.html
ErrorDocument 500 /servererror.html

Password Protect Directories

With this Directories, you will need two files, ".htaccess" and ".htpasswd". The .htpasswd file needs to include some encryption. A tool like Htpasswd Generator to create the file works good.

The .htaccess file should include this code;

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /path/to/.htpasswd
Require valid-user

Setting the Default Directory Page

Most default website directory pages are named "index.html". If you want your default to be something else like "home.html" use this format.

DirectoryIndex home.html

Enabling SSI

Some web hosting servers will have Server Side Includes enabled by default. If not, you can enable it with your .htaccess file.

AddType text/html .shtml
AddHandler server-parsed .shtml
Options Indexes FollowSymLinks Includes
WordPress hosting

Removing file Extensions such as .PHP

For our example we will use this page, the full name is actually:

But with this code it becomes just:

This looks cleaner in your Browsers address bar, and Google even uses this cleaner looking version of the URL in the search results.

You can remove any file extension by substituting the ".php" for your extension.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]

Disable Directory Browsing

This is one of the easiest to do and only needs two lines of code to be included in your .htaccess file.

Options -Indexes

Force Files to Download Instead of Showing in Browser

Have you ever clicked a PDF link and had it open in your browser instead of downloading? Or an MP3 starts playing right there? That’s the browser’s default behavior for certain file types: PDFs, images, audio, and video often display inline. With .htaccess, you can force these files to download instead, giving the user a file they can save and open later.

AddType application/octet-stream .mov .mp3 .zip

Disallow Script Execution

This would be use if you do not want scripts such as CGI or PHP to run.

Options -ExecCGI
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Password

Redirect an entire Website

If you need to move your whole site, an example might be if your switching from a "olddomain.com" name to a "newdomain.com", or shifting from HTTP to HTTPS for security. Redirecting every page manually can be a nightmare, but with a .htaccess file you can handle it in just a few lines of code, sending all traffic to a new destination. It is also great for SEO (keeping your search rankings) and user experience (no broken links).

Redirect 301 / https://example.com/

Redirect a page on the same domain

Redirect 301 /page.html /newpage.html

Redirect a page to a different domain

Redirect 301 /page.html https://example.com/page.html

Redirect from .html to .php

Switching your site from static .html pages to dynamic .php ones is a common upgrade. With .htaccess, you can seamlessly redirect all .html requests to their .php equivalents (e.g., page.html to page.php), keeping everything working properly.

RedirectMatch 301 (.*)\.html https://example.com/$1.php
SSH

Remove WWW from all URLs

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule (.*) https://example.com/$1 [R=301,L]

Force HTTP to HTTPS

If your site has an SSL certificate (most hosts offer free ones via cPanel), you can use .htaccess to redirect all HTTP traffic (e.g., http://yourdomain.com) to HTTPS (e.g., https://yourdomain.com). It’s a simple tweak that boosts security, trust and stops Browser Warnings.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
Quality Content

.htaccess and Page Speed

Page speed isn't just about keeping visitors happy, it's a big deal for SEO and user experience. A slow site can drive people away and tank your Google rankings. Luckily, the .htaccess file offers simple tricks to speed things up, no coding degree required.

  • • Enable Compression: Big files (HTML, CSS, JavaScript) take longer to load. Compression shrinks them before they're sent to browsers
  • • Leverage Browser Caching: (covered below) Why make browsers download the same logo or stylesheet every visit? Caching stores files locally on a user's device:
  • • Remove File Extensions: Stripping .php or .html (covered earlier) doesn't directly speed up pages, but it simplifies URL handling, which can streamline server processing
  • • Hosting Support: Compression and caching need Apache modules (mod_deflate, mod_expires). Check with your host if they're enabled.
  • • Testing: After changes, use tools like Pingdom or Lighthouse to measure improvement.
Website Hosting

Leverage Browser Caching

One of the easiest ways to increase site speed and reduce server load is to leverage browser caching. Browser caching stores resources from your website page on a visitor's computer.

RewriteBase /
# compress text, HTML, JavaScript, CSS, and XML
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE image/svg+xml
</ifmodule>
# remove browser bugs
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType video/mp4 "access plus 1 year"
ExpiresByType audio/mp3 "access plus 1 year"
ExpiresByType video/mpeg "access plus 1 year"
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 1 month"
ExpiresByType font/ttf "access plus 1 year"
ExpiresByType font/otf "access plus 1 year"
ExpiresByType font/woff "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType application/font-woff "access plus 1 year"
</IfModule>
## EXPIRES CACHING ##

When Not to use the .htaccess file

In general, you should only use the .htaccess files when you do not have access to your main Server configuration files. There is, for example, a common misconception that user authentication should always be done with the .htaccess files, and in more recent years another misconception that mod_rewrite directives must go in the .htaccess files. This is simply not the case. You can add user authentication configurations in the main Servers configuration, and this is the preferred way to do this. Likewise, mod_rewrite directives work better and in many respects faster with better security.

The .htaccess files should be used in cases where the content providers need to make configuration changes to the Server on a "Per Directory" basis. But do not have root access to the Web Server system. Or in the event that the server administrator is not willing to make frequent configuration changes, it might be desirable to permit individual users to make these changes for themselves. This is particularly true, for example, in cases where hosting companies are hosting multiple websites on a single Server. And allow their users to be able to alter their own website's configuration.

There are two main reasons to avoid the use of the .htaccess files.

Performance. When AllowOverride is set to allow the use of .htaccess files, HTTPD will look in every directory for other .htaccess files. As a result, permitting, .htaccess files causes a performance hit. Whether there are any others. Also, the .htaccess file "Loads" every time a document is requested.

Security. You are permitting users to modify Server configurations. This could result in changes over which you have no control. Carefully consider whether you want to give your users this privilege. Note also that giving users less privileges than they need will lead to additional technical support requests. Make sure you clearly tell your users what level of privileges you have given them. Specifying exactly what you have set AllowOverride to, and pointing them to the relevant documentation, will save yourself a lot of confusion later.

Blog Hosting

cPanel Hosting Tips

Most website hosting companies use cPanel on shared Apache servers. It's great for simplicity but comes with limits:

  • • Restricted Access: You can't edit Apache's main config (httpd.conf), so .htaccess is your only tool. If AllowOverride is set to None by the host (rare but possible), your file won't work.
  • • File Manager Hiccups: cPanel's File Manager hides "dot-files" by default. You might think it is not there. To show these files. Click “Settings” and check “Show Hidden Files.”
  • • Missing File: If you are missing the .htaccess file you can create one or ask your support team to make one for you (if they wont - find a different host)
  • • Caching Delays: Some hosts "cache" their config files, so changes might not show instantly. Try clearing your browser cache or wait a few minutes.
  • • Testing: Test a basic rule like Redirect /test /
  • • Check the Result: If you landed on your homepage (yourdomain.com/) all is working. If you get a 404 error or you see no change, the .htaccess file isn't working yet.

Common Mistakes and Troubleshooting

When you are new to the .htaccess file and editing it, things can go wrong fast, and they often do.
Just a tiny typo might break your site with a dreaded 500 Internal Server Error

Here's how to avoid them:

  • • Syntax Errors: A misplaced space can cause a 500 error. Double-check your code.
  • • Permissions: Ensure the file is readable (e.g., chmod 644).
  • • RewriteEngine Not Enabled: Rules like RewriteRule won't work without: RewriteEngine On Skip this, and nothing will happen.
  • • Server Config Conflicts: Your host might disable "AllowOverride" blocking .htaccess entirely. Contact your Support Team to confirm "AllowOverride" is set to All.
  • • Testing: Use tools like htaccess.madewithlove.com to simulate rules.
  • • If your site breaks: Try renaming the .htaccess file to disable it temporarily and fix the issue.

Summary

.htaccess might be an old school tool, but it still has an important role to play with certain functions of your website. Almost all Apache Servers have a preset configuration file. But this applies to the whole Web Server. That is where the .htaccess can can come in handy. You can set directory and subdirectory level configuration to override the Apache configuration settings. Or to set specific configuration rules for your website.

Author Bio:

A guest blogger hailing from Switzerland, dedicated to assisting local companies in expanding their reach from regional to national and international levels. With a proven track record in...

We welcome your comments, questions, corrections and additional information relating to this article. Please be aware that off-topic comments will be deleted.
If you need specific help with your account, feel free to contact us anytime
Thank you

Tweet  Share  Pin  Email

Inspired by the ingenuity of our master copywriters

Offering cPanel, SSL Certs, Free Domains and Private Registration with every website hosting package