How To Use .htaccess To Modify Your Website Behavior

What is .htaccess?

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

WARNINGS: .htaccess files listed here are for people that do not have rights to edit the main server configuration file. You should avoid using .htaccess files completely especially when you have access to httpd main server config file not only because it slows down a server, but also that monkeying around with your .htaccess without having a proper understanding on how it works will break your server or website.

There is also the consideration of security. If you are a "root" user, you are permitting users to modify server configuration, which may 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 fewer 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.

The examples here are offered "as it is" without any guarantee that they will work in your environment. Please double check, test and verify any rules before applying them to your .htaccess. If you do not understand a rule, do not use it; consult someone who does.

Backup your existing .htaccess file before making any changes to it.

That way you can move it back if your website or server becomes unresponsive.

Rewrite and Redirection Rules

(Note: It is assumed that you have `mod_rewrite` installed and enabled. The first line should be 'RewriteEngine on' to enable this)

Serve All Requests With One PHP File with .htaccess perm link
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*)$ /index.php [NC,L,QSA]

(This is the only rule in this section that includes the RewriteEngine on rule)

# BEGIN WordPress
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
# END WordPress
Turn off directory indexes

Directory indexing which allows visitors to view a list of files instead of the actual webpage is enabled by default at Hostragon. With this enabled, visitors can look inside any directory that does not have an index.html (or index.php, etc.) file in it and browse the contents of the directory. This is probably not the behavior you typically want, especially if said directory contains something like script configuration files that could pose a security risk.

To turn off directory indexing, place the following line in a .htaccess file in your domain's folder to disable directory indexes throughout your entire site: <

Options -Indexes

Now when someone visits a directory or folder that has no index file, it will receive a Forbidden error instead of seeing a list of the directory's contents. The error indicates the visitor does not have access permissions to view that area.

To turn on directory indexes for specific folders:

If there's a particular directory in your site that you do want people to be able to browse, simply create a new .htaccess file in that particular folder. Add the following:

Options +Indexes
Force www with .htaccess perm link
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$$1 [L,R=301,NC]
Force www in a Generic Way with .htaccess perm link
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

This works for any domain. Source

Force non-www with .htaccess perm link

It's still open for debate whether www or non-www is the master race, so if you happen to be a fan or bare domains, here you go:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$$1 [L,R=301]
Force non-www in a Generic Way with .htaccess perm link
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]
Force HTTPS with .htaccess perm link

Use this to redirect non HTTPS requests to a HTTPS request. I.e. if you go to it will redirect to

RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

It is recommended to use HSTS (read about it on Wikipedia) though.

"HTTP Strict Transport Security (HSTS) is a web security policy mechanism which is necessary to protect secure HTTPS websites against downgrade attacks, and which greatly simplifies protection against cookie hijacking. It allows web servers to declare that web browsers (or other complying user agents) should only interact with it using secure HTTPS connections, and never via the insecure HTTP protocol. HSTS is an IETF standards track protocol and is specified in RFC 6797."

Force HTTPS Behind a Proxy with .htaccess perm link

Useful if you have a proxy in front of your server performing TLS termination.

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Force Trailing Slash with .htaccess perm link

Use the following .htaccess rule to redirect any URLs to the same URL (but with a trailing slash) for any requests that do not end with a trailing slash. I.e. redirect from to

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
Remove Trailing Slash with .htaccess perm link

Use this to remove any trailing slash (it will 301 redirect to the non-trailing slash URLl)

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]
Redirect a Single Page with .htaccess perm link

Redirect a single URL to a new location

Redirect 301 /oldpage.html
Redirect 301 /oldpage2.html


Alias a Single Directory with .htaccess perm link
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1
Alias Paths To Script with .htaccess perm link
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]

This example has an index.fcgi file in some directory, and any requests within that directory that fail to resolve a filename/directory will be sent to the index.fcgi script. It's good if you want to be handled by (which also supports requests to while maintaining and the like.

Redirect an Entire Site with .htaccess perm link

Use the following .htaccess rule to redirect an entire site to a new location/domain

Redirect 301 /

This way does it with links intact. That is will become This is extremely helpful when you are just "moving" a site to a new domain.


Alias "Clean" URLs with .htaccess perm link

This snippet lets you use "clean URLs" -- those without a PHP extension, e.g. instead of

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]



Security Rules

Deny All Access with .htaccess perm link

If you want to prevent apache serving any files at all, use the following.

Apache 2.2:
Deny from all
Apache 2.2:
# Require all denied

This will stop you from accessing your website. If you want to deny all access but still be able to view it yourself please read the next rule:

Deny All Access Except Yours (Only allow certain IPs) with .htaccess perm link

Use this to ONLY allow certain IP addresses to access your website.

Apache 2.2
Order deny,allow
Deny from all
Allow from
Apache 2.4
# Require all denied
# Require ip is your IP. If you replace the last three digits with 0/12 for example, this will specify a range of IPs within the same network, thus saving you the trouble to list all allowed IPs separately. Source

Please see the next rule for the 'opposite' of this rule!

Block IP Address with .htaccess perm link

This will allow access to all IPs EXCEPT the ones listed. You can use this to allow all access Except Spammer's IP addresses.

Replace and with the IP addresses you want to block.

Apache 2.2
Order deny,allow
Allow from all
Deny from
Deny from
Apache 2.4
# Require all granted
# Require not ip
# Require not ip
Allow access only from LAN with .htaccess perm link
order deny,allow
deny from all
allow from
Deny Access To Certain User Agents (bots) with .htaccess perm link

Use this .htaccess rule to block/ban certain user agents

RewriteCond %{HTTP_USER_AGENT} ^User\ Agent\ 1 [OR]
RewriteCond %{HTTP_USER_AGENT} ^Another\ Bot\ You\ Want\ To\ Block [OR]
RewriteCond %{HTTP_USER_AGENT} ^Another\ UA
RewriteRule ^.* - [F,L]
Deny Access to Hidden Files and Directories with .htaccess perm link

Hidden files and directories (those whose names start with a dot .) should most, if not all, of the time, be secured.

For example: .htaccess, .htpasswd, .git, .hg...

RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]

Alternatively, you can just raise a Not Found error, giving the attacker dude no clue:

RedirectMatch 404 /\..*$
Deny Access To Certain Files with .htaccess perm link

Use this to block or deny access to certain files

<files your-file-name.txt>
order allow,deny
deny from all
Deny Access to Backup and Source Files with .htaccess perm link

These files may be left by some text/html editors (like Vi/Vim) and pose a great security danger, when anyone can access them.

<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
    ## Apache 2.2
    Order allow,deny
    Deny from all
    Satisfy All

    ## Apache 2.4
    # Require all denied


Disable Directory Browsing with .htaccess perm link
Options All -Indexes
Enable Directory Listings with .htaccess perm link
Options All +Indexes
Disable Listing Of Certain Filetypes (if Indexes is not disabled) with .htaccess perm link

Use this to exclude certain file types from being listed in Apache directory listing. You could use this to stop .pdf files, or video files showing up.

IndexIgnore *.zip *.mp4 *.pdf
Disable Image Hotlinking with .htaccess perm link
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
Redirect hotlinkers and show a different image with .htaccess perm link
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?*$ [NC]
RewriteRule \.(gif|jpg|png)$ [R,L]
Deny Access from certain referrers with .htaccess perm link

Use this rule to block access to requests that include a referrer from a certain domain.

RewriteCond %{HTTP_REFERER} block-this-referer\.com [NC,OR]
RewriteCond %{HTTP_REFERER} and-block-traffic-that-this-site-sends\.com [NC]
RewriteRule .* - [F]
Password Protect a Directory with .htaccess perm link

First, you need to create a .htpasswd file somewhere in the system. Run the following command at the command line:

htpasswd -c /home/hidden/directory/here/.htpasswd the_username

Then you can use it for authentication. In your .htaccess file you need something like the following code, but make sure the AuthUserFile is the file path to the .htpasswd you just created. You should keep the .htpasswd in a directory not accessible via the web. So don't put it in your /public_html/ or /www/ directory.

AuthType Basic
AuthName "Password Protected Dir Title"
AuthUserFile /home/hidden/directory/here/.htpasswd
Require valid-user
Password Protect a File or Several Files with .htaccess perm link
AuthName "Password Protected Directory Title"
AuthType Basic
AuthUserFile /home/hidden/directory/here/.htpasswd

<Files "a-private-file.txt">
Require valid-user

<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user

Performance Rules

Compress Text Files (gzip/deflate output) with .htaccess perm link
<IfModule mod_deflate.c>

        # Force compression for mangled headers.
        <IfModule mod_setenvif.c>
                <IfModule mod_headers.c>
                        SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
                        RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding

        # Compress all output labeled with one of the following MIME-types
        # (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
        #    and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines
        #    as `AddOutputFilterByType` is still in the core directives).
        <IfModule mod_filter.c>
            AddOutputFilterByType DEFLATE application/atom+xml \
              application/javascript \
              application/json \
              application/rss+xml \
              application/ \
              application/x-font-ttf \
              application/x-web-app-manifest+json \
              application/xhtml+xml \
              application/xml \
              font/opentype \
              image/svg+xml \
              image/x-icon \
              text/css \
              text/html \
              text/plain \
              text/x-component \



Set Expires Headers with .htaccess perm link

Expires headers tell the browser whether they should request a specific file from the server or just grab it from the cache. It is advisable to set static content's expires headers to something far in the future.

If you don't control versioning with filename-based cache busting, consider lowering the cache time for resources like CSS and JS to something like 1 week. Source

<IfModule mod_expires.c>
        ExpiresActive on
        ExpiresDefault                                    "access plus 1 month"

    # CSS
        ExpiresByType text/css                            "access plus 1 year"

    # Data interchange
        ExpiresByType application/json                    "access plus 0 seconds"
        ExpiresByType application/xml                     "access plus 0 seconds"
        ExpiresByType text/xml                            "access plus 0 seconds"

    # Favicon (cannot be renamed!)
        ExpiresByType image/x-icon                        "access plus 1 week"

    # HTML components (HTCs)
        ExpiresByType text/x-component                    "access plus 1 month"

    # HTML
        ExpiresByType text/html                           "access plus 0 seconds"

    # JavaScript
        ExpiresByType application/javascript              "access plus 1 year"

    # Manifest files
        ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"
        ExpiresByType text/cache-manifest                 "access plus 0 seconds"

    # Media
        ExpiresByType audio/ogg                           "access plus 1 month"
        ExpiresByType image/gif                           "access plus 1 month"
        ExpiresByType image/jpeg                          "access plus 1 month"
        ExpiresByType image/png                           "access plus 1 month"
        ExpiresByType video/mp4                           "access plus 1 month"
        ExpiresByType video/ogg                           "access plus 1 month"
        ExpiresByType video/webm                          "access plus 1 month"

    # Web feeds
        ExpiresByType application/atom+xml                "access plus 1 hour"
        ExpiresByType application/rss+xml                 "access plus 1 hour"

    # Web fonts
        ExpiresByType application/font-woff2              "access plus 1 month"
        ExpiresByType application/font-woff               "access plus 1 month"
        ExpiresByType application/       "access plus 1 month"
        ExpiresByType application/x-font-ttf              "access plus 1 month"
        ExpiresByType font/opentype                       "access plus 1 month"
        ExpiresByType image/svg+xml                       "access plus 1 month"
Turn eTags Off with .htaccess perm link

By removing the ETag header, you disable caches and browsers from being able to validate files, so they are forced to rely on your Cache-Control and Expires header. Source

<IfModule mod_headers.c>
        Header unset ETag
FileETag None
Limit Upload File Size with .htaccess perm link

Put the file size in bytes. See here for a conversion tool. The code below limits it to 1mb.

LimitRequestBody 1048576

Miscellaneous Rules

Server Variables for mod_re­write with .htaccess perm link
Set PHP Variables with .htaccess perm link
php_value <key> <val>
For example:
php_value upload_max_filesize 50M
php_value max_execution_time 240
Custom Error Pages with .htaccess perm link
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401
ErrorDocument 404 /errors/halflife3.html
Redirect users to a maintenance page while you update with .htaccess perm link

This will redirect users to a maintenance page but allow access to your IP address. Change 555.555.555.555 to your IP, and YourMaintenancePageFilenameOrFullUrlUrl.html to your error page (or a whole URL, on a different domain).

ErrorDocument 403 YourMaintenancePageFilenameOrFullUrlUrl.html
Order deny,allow
Deny from all
Allow from 555.555.555.555
Force Downloading with .htaccess perm link

Sometimes you want to force the browser to download some content instead of displaying it. The following snippet will help.

<Files *.md>
        ForceType application/octet-stream
        Header set Content-Disposition attachment
Disable Showing Server Info (Server Signature) with .htaccess perm link

While many people consider this pointless (especially with regards to security), if you want to stop your server from giving away server info (the sever OS etc), use this:

ServerSignature Off
Prevent Downloading with .htaccess perm link

Sometimes you want to force the browser to display some content instead of downloading it. The following snippet will help.

<FilesMatch "\.(tex|log|aux)$">
        Header set Content-Type text/plain
Allow Cross-Domain Fonts with .htaccess perm link

CDN-served web fonts might not work in Firefox or IE due to CORS. The following snippet from alrra should make it happen.

<IfModule mod_headers.c>
        <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
                Header set Access-Control-Allow-Origin "*"
Auto UTF-8 Encode with .htaccess perm link

To have Apache automatically encode your content in UTF-8, use the following code. You can also swap the utf-8 for another character set if required:

# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8

# Force UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml


Set Server Timezone (to UTC, or other time zone) with .htaccess perm link

See a list of time zones here. To set it to Los Angeles time zone:

SetEnv TZ America/Los_Angeles
Switch to Another PHP Version with .htaccess perm link

If you're on a shared host, chances are there are more than one version of PHP installed, and sometimes you want a specific version for your website. For example, Laravel requires PHP >= 5.4. The following snippet should switch the PHP version for you.

AddHandler application/x-httpd-php55 .php
Alternatively, you can use AddType
AddType application/x-httpd-php55 .php

Disable Internet Explorer Compatibility View

Compatibility View in IE may affect how some websites are displayed. The following snippet should force IE to use the Edge Rendering Engine and disable the Compatibility View.

<IfModule mod_headers.c>
    BrowserMatch MSIE is-msie
    Header set X-UA-Compatible IE=edge env=is-msie
Execute PHP with a different file extension with .htaccess perm link

The following code will run files ending in .ext with php:

AddType application/x-httpd-php .ext

Serve WebP Images Automatically If They Exist

If WebP images are supported and an image with a .webp extension and the same name is found at the same place as the jpg/png image that is going to be served, then the WebP image is served instead.

RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]

Troubleshooting (root users ONLY) :

When you put configuration directives in a .htaccess file, check the syntax with:

apachectl -t

It parses the configuration files and either reports Syntax Ok or detailed information about the particular syntax error.

  • htaccess
  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

How To Deal With "508 Resource Limit Is Reached" or "Entry Process Limit" Issue

Resource limit errors can happen due to a variety of reasons. Entry Process limit can be reached...

How To Deal With phpMyAdmin "Unknown collation" Error In cPanel

How To Deal With phpMyAdmin "Unknown collation" Error In cPanel The unknown collation error is...

How to Connect to cPanel Web Disk From Your Mobile Device

You can connect to cPanel's Web Disk from your mobile device using cPanel's Inc supplied iOS and...

What Is Domain Name or What Are Domain Names?

In technical terms, a domain name is an identification string that defines a realm of...

What Is A Domain Registration?

Simply put, a domain registration is a process of acquiring a domain name from a domain name...

Powered by WHMCompleteSolution