Top 24 Cool and Most Useful .htaccess Hacks

Do you want to Improve your Website Users Experience and protect from Hackers?

A .htaccess file can be used for lots of hacks that will secure and improve functionality for WordPress blogs and websites.
In this Article I will share Top 24 cool htaccess Hacks that will Improve your Website Users Experiece and Prevent your Website (WordPress) from Hackers.

The .htaccess(hypertext access) file is a directory-level configuration file supported by several web servers, which allows for decentralized management of web server configuration.


Do You know that When your Website get Hacked?

No (even I don’t know).

But, We can try to Protect it from Hackers.(I’m also facing regular attack on my WordPress website).

There are several ways to Protect your Website from Hackers or getting Hacked.

1. Block Access to Sensitive files

Block access to files that can expose sensitive information.

By default, block access to backup and source files that may be left by some text editors and can pose a security risk when anyone has access to them.

<FilesMatch "(^#.*#|\.(bak|conf|dist|fla|in[ci]|log|psd|sh|sql|sw[op]|[Hh][Tt][Aa]|)~)$">

    # Apache < 2.3
    <IfModule !mod_authz_core.c>
        Order allow,deny
        Deny from all
        Satisfy All

    # Apache ??? 2.3
    <IfModule mod_authz_core.c>
        Require all denied


Update the regular expression from above to include any files that might end up on your production server and can expose sensitive information about your website.

These files may include: configuration files, files that contain metadata about the project (e.g.: project dependencies), build scripts, etc..

2. Blacklist Undesired Users and Bots IP

You can Blacklist Undesired User and Bots IP and allow certain IP’s only.

deny from all
# whitelist Shubhams's IP address
allow from
# whitelist Sachin's IP address
allow from
# whitelist Vivek's IP address
allow from

Replace with your own IP address. If you are using more than one IP address to access the internet, then make sure you add them as well.

3. Block access to directories without a default document

With directory browsing enabled, hackers can look into your website’s directory and file structure to find a vulnerable file.

Many Security experts recomment disabling directory browsing.

<IfModule mod_autoindex.c>
    Options -Indexes

Disabled Directory Browsing

4. Reducing MIME type security risks

This reduces exposure to drive-by download attacks and cross-origin data leaks, and should be left uncommented, especially if the server is serving user-uploaded content or content that could potentially be treated as executable by the browser.

<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"

5. Protect website against Clickjacking

The example below sends the X-Frame-Options response header with the value DENY, informing browsers not to display the content of the web page in any frame.

Note: This might not be the best setting for everyone.

You should read about the other two possible values the X-Frame-Options header field can have: SAMEORIGIN and ALLOW-FROM. [Read here]

<IfModule mod_headers.c>
     Header set X-Frame-Options "DENY"
     # `mod_headers` cannot match based on the content-type, however,
     # the `X-Frame-Options` response header should be send only for
     # HTML documents and not for the other resources.
     <FilesMatch "\.(appcache|atom|bbaw|bmp|crx|css|cur|eot|f4[abpv]|flv|geojson|gif|htc|ico|jpe?g|js|json(ld)?|m4[av]|manifest|map|mp4|oex|og[agv]|opus|otf|pdf|png|rdf|rss|safariextz|svgz?|swf|topojson|tt|txt|vcard|vcf|vtt|webapp|web[mp]|woff2?|xloc|xml|xpi)$">
         Header unset X-Frame-Options

6. Content Security Policy (CSP)

Mitigate the risk of cross-site scripting and other content-injection attacks.This can be done by setting a Content Security Policy which whitelists trusted sources of content for your website.

<IfModule mod_headers.c>

    Header set Content-Security-Policy "script-src 'self'; object-src 'self'"

    # `mod_headers` cannot match based on the content-type, however,
    # the `Content-Security-Policy` response header should be send
    # only for HTML documents and not for the other resources.

    <FilesMatch "\.(appcache|atom|bbaw|bmp|crx|css|cur|eot|f4[abpv]|flv|geojson|gif|htc|ico|jpe?g|js|json(ld)?|m4[av]|manifest|map|mp4|oex|og[agv]|opus|otf|pdf|png|rdf|rss|safariextz|svgz?|swf|topojson|tt|txt|vcard|vcf|vtt|webapp|web[mp]|woff2?|xloc|xml|xpi)$">
        Header unset Content-Security-Policy

The example header above allows ONLY scripts that are loaded from the current website’s origin (no inline scripts, no CDN, etc).

That almost certainly won’t work as-is for your website!

7. Protect .htaccess and wp-config.php file From Unauthorized Access

As you have seen that lot of things can be done using htaccess and wp-config.php contains sensitive informations.Due to the power and control it has on your web server, it is important that you protect it from unauthorized access by hackers.

Simply add this code to your .htaccess file:

<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
<files wp-config.php>
order allow,deny
deny from all

8.Disable Image Hotlinking in WordPress

If you wants to know what exactly is Hotlink, then visit Wikipedia.

If you run a popular site with lots of images and photos, then hotlinking can become a serious issue. You can prevent image hotlinking by adding this code in your .htaccess file:

#disable hotlinking of images with forbidden or custom image option
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ – [NC,F,L] 

Above example will only allow, and feedburner to access your Website images.

10. Stop Spam Comments

Below Example will Deny comment posting to no referrer requests.

RewriteEngine On
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.** [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

Replace to your website url.

11. Limit Maximum File upload size to 50MB

Below example will limit maximum file upload size to 50MB.

# limit file uploads to 50mb
LimitRequestBody ‪52428800‬

12. Secure Plugin Files

You can secure your WordPress plugins javascript and css files using below code:

<Files ~ ".(js|css)$">
  order allow,deny
  allow from all

First you need to create a .htpasswds file.

Rich User Experience

As we have seen some cool ways to Provide security to your Website.Now, it’s time to leverage your User Experience and functionality.

13. Compress Contents with GZip

You can speed up your website by compressing its content using htaccess GZip compression.

GZip Compressed MyCodingTricks

You can compress 80% of your Content using the below code:

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent

14. Leverage Browser Caching

Serve resources with far-future expires headers.

Setting an expiry date or a maximum age for static resources in the HTTP headers instructs the browser to load previously downloaded resources from local disk.

<IfModule mod_expires.c>

    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

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

  # Data interchange
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rdf+xml                   "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/ld+json                   "access plus 0 seconds"
    ExpiresByType application/schema+json               "access plus 0 seconds"
    ExpiresByType application/vnd.geo+json              "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

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

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

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"
    ExpiresByType application/x-javascript              "access plus 1 year"
    ExpiresByType text/javascript                       "access plus 1 year"

  # Manifest files
    ExpiresByType application/manifest+json             "access plus 1 year"

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

  # Media files
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/bmp                             "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 image/svg+xml                         "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 fonts

    # Embedded OpenType (EOT)
    ExpiresByType application/         "access plus 1 month"
    ExpiresByType font/eot                              "access plus 1 month"

    # OpenType
    ExpiresByType font/opentype                         "access plus 1 month"

    # TrueType
    ExpiresByType application/x-font-ttf                "access plus 1 month"

    # Web Open Font Format (WOFF) 1.0
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/x-font-woff               "access plus 1 month"
    ExpiresByType font/woff                             "access plus 1 month"

    # Web Open Font Format (WOFF) 2.0
    ExpiresByType application/font-woff2                "access plus 1 month"

  # Other
    ExpiresByType text/x-cross-domain-policy            "access plus 1 week"


15. File concatenation

Allow concatenation from within specific files.
For Example : If you have the following lines in a file called, for example,scripts.combined.js Apache will replace those lines with the content of the specified files.

       <!--#include file="js/jquery.js" -->
       <!--#include file="js/jquery.timer.js" -->
Note: Must end your css or javascript files with .combined.js extension for concatenation.

Use the below code for file concatenation:

<IfModule mod_include.c>
    <FilesMatch "\.combined\.js$">
        Options +Includes
        AddOutputFilterByType INCLUDES application/javascript \
                                       application/x-javascript \
        SetOutputFilter INCLUDES
    <FilesMatch "\.combined\.css$">
        Options +Includes
        AddOutputFilterByType INCLUDES text/css
        SetOutputFilter INCLUDES

16. Customized error pages

If you’d like to redirect your visitors every time they catch into an HTTP 404 error OR Some other HTTP Error, use this code:

# custom error pages
ErrorDocument 401 /error/401.php
ErrorDocument 403 /error/403.php
ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php

17. Add Trailing Slash to URL

You can add Trailing Slash to URL if it doesn’t have.Use the below code to add trailing slash:

#trailing slash enforcement
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !#
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$$1/ [L,R=301]

Replace to your website url.

18. Redirect www to non www or vice versa

To Redirect www to non-www use this code:

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

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

And if you wants to redirect non-www to www:

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]

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

19. Redirect WordPress Feeds to FeedBurner

You can Redirect your WordPress Feeds to Feedburner using the below code:

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_USER_AGENT} !FeedBurner    [NC]
 RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC]
 RewriteRule ^feed/?([_0-9a-z-]+)?/?$ [R=302,NC,L]

20. Redirect WordPress Comment Feeds to FeedBurner

You can Redirect WordPress Comment Feeds to FeedBurner using the below code:

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_USER_AGENT} !FeedBurner    [NC]
 RewriteCond %{HTTP_USER_AGENT} !FeedValidator [NC]
 RewriteRule ^comments/feed/?([_0-9a-z-]+)?/?$ [R=302,NC,L]

21. Redirect to a Different URL

You can Redirect one Url to a Different URL using htaccess:

Redirect 301 /directory/file.html

22. Redirect visitors to a maintenance page

You can Redirect your visitor to maintanance page using below code:

RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123
RewriteRule $ /maintenance.html [R=302,L]

23. Allow ‘Access-Control-Allow-Origin’

Use below to allow ‘Access-Control-Allow-Origin’ using htaccess:

Header set Access-Control-Allow-Origin: *

24. Pretty URL Rewrite with htaccess

Your can create pretty url(e.g: from ugly url(e.g.: with htaccess.

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^search/(.*)$ ./search.php?s=$1


You can use Above htaccess hacks to Create a Awesome Website secured from Hackers and Rich User experience.You can use above codes for your WordPress website also.

If you liked the Article then please Share it.

Do you have any other htaccess Hack?

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

Leave a Reply

Your email address will not be published. Required fields are marked *