How to secure and protect WordPress through .htaccess File


With the help of the .htaccess (hypertext access) file, you can get a directory-level configuration, allowing you to decentralize the management of your web server configuration. It also allows you to improve your blog’s security and reduce bandwidth. Today, we compile a list of tips and hack to increase your WordPress website security through the .htaccess file. If you like these tips and hacks, please grab the WPArena RSS feed to keep yourself up to date! Here are the contents of this guide.

Note: Be careful to make changes in this file because modifying the configuration of a server can cause security concerns if not set up correctly. So always have a Backup.


Restrict access to the Backend (wp-admin) Area

There are different ways to protect your wp-admin. By using WordPress plugins “enhance WordPress security with two-factor authentication plugins” and by adding a .htaccess file into a wp-admin directory like:

By restricting the IP address and create a .htaccess file including the following piece of code:

order deny,allow
allow from a.b.c.d # This is your static IP
deny from all

By limiting the directory with a password:

AuthUserFile /etc/httpd/htpasswd
AuthType Basic
AuthName "restricted"
Order Deny,Allow
Deny from all
Require valid-user
Satisfy any

Individually Blacklist IP Address

There are a considerable number of spammers, scrapers, and crackers; those need to be blacklisted to visit the site. Perishable Press every year blocks some IP addresses every year, and they give solutions on how to block an IP address by using the .htaccess file:

<Limit GET POST PUT> order allow,deny allow from all deny from </LIMIT>

Ultimate IP Blocker

Want to ban an IP but don’t know how to use .htaccess and only ban for some pages? Let ipBlocker help you ban IP(s) with many functions; no need for any database support.

Protecting WordPress wp-config file

Add the following piece of code in the .htaccess file to protect the wp-config file:

# protect wpconfig.php <files wp-config.php> order allow,deny deny from all </files>

How To Disable Directory Browsing using .htaccess

# disable directory browsing Options All -Indexes

Disables image hotlinking

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

Redirect WordPress Feeds to Feedburner via. .htaccess

.htaccess is a powerful tool that also helps to redirect WordPress feeds to Feedburner.

Redirecting your WordPress feeds to Feedburner enables you to take advantage of their many freely provided, highly useful tracking and statistical services. Although there are a few important things to consider beforeoptimizing your feeds and switching to Feedburner, many WordPress users redirect their blog’s two main feeds — “main content” and “all comments” — using either a plugin or directly via htaccess.

We have consolidated the previous .htaccess code into a single redirect for those using Feedburner for all content and comment feeds. Additionally, we improve functionality by verifying the requested URI and simplifying the regex used to match the target string. Check it out:

# temp redirect WordPress content feeds to feedburner 
<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]

IP Delivery to Stop RSS “Content Thieves”

“uads Zilla at Seo Black Hat explained how to know IP addresses of who is stealing your RSS Feed and how to block IP addresses through the .htaccess file.

RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^
RewriteRule ^(.*)$

How to set up a maintenance page with the .htaccess file?

If you want to migrate your blog, switch themes, or update WordPress, why not redirect your visitors to a maintenance page.

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

Deny no referer requests [stop spam comments!]

If there are lots of spam comments on your blog, along with Akismet, you can stop spam comments with .htaccess to prevent spammers from posting comments on your blog.

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

Force the “File Save As” “prompt

Using this code, you can force users not to open downloadable files. Instead, you force them to save as:

AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4

Improve Site Security by Protecting HTAccess Files

Jeff Starr presents on Perishable Press different methods to protect the .htaccess file. The following code below prevents external access to any file with .htaccess. Add the code below in your domain’s root .htaccess file.

Case-sensitive protection:

order allow,deny
deny from all

Weak pattern matching

<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy All

Strong pattern matching

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

.htaccess – gzip and cache for faster loading and bandwidth saving

To speed up the site and save bandwidth, you can use .htaccess, a file to gzip text-based files, and optimize cache HTTP headers.

If your hosting provider like  has the mod_gzip module enabled, the best way to compress your content is to add the following lines to your .htaccess file:

mod_gzip_on Yes
  mod_gzip_dechunk Yes
  mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
  mod_gzip_item_include handler ^cgi-script$
  mod_gzip_item_include mime ^text/.*
  mod_gzip_item_include mime ^application/x-javascript.*
  mod_gzip_item_exclude mime ^image/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

Source – There are other different ways for fast loading and saving bandwidth on:
.htaccess – gzip and cache your site for faster loading and bandwidth saving
WordPress Super Cache: Makes WordPress Faster

WordPress Safer Admin Plugin

Have you ever wondered how you could hide your WordPress Admin Panel so possible attackers won’t be able to find it and gain access to your WordPress site?

If you want to ensure that no one knows where your WordPress Admin Panel is, this WP Safer Admin Plugin is the right tool for you!


WP-Restrict is a WordPress plugin that allows WordPress admins to restrict access to their website based on IP addresses.

Redirecting Subdirectories to the Root Directory via HTAccess

One of the most useful techniques in my HTAccess toolbox involves URL redirection using Apache’s RedirectMatch directive. With RedirectMatch, you get the powerful regex pattern matching available in the mod_alias module combined with the simplicity and effectiveness of the Redirect directive.

RedirectMatch 301 ^/blog/.*$

Removing Category Base from WordPress URLs

The below .htaccess code illustrates two different ways to redirect any request./cIt will help if you gory/slug/ to /slug/ You only redirected after applying the PHP hacks described earlier. Otherwise, you could end up creating a loop.

RedirectMatch 301 ^/category/(.+)$ 
# OR
RewriteRule ^category/(.+)$  [R=301,L]

Valiantly automatically fix URL spelling mistakes

This directive can be helpful in auto-correct simple spelling errors in the URL

<IfModule mod_speling.c>
CheckSpelling On

Redirect the spammers where you want

Here is the script to add to your WordPress blogs (or into your sisite’s.htaccess file:

# block comment spam by denying access to no-referrer requests
RewriteEngine On
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.** [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule ^(.*)$ ^$ [R=301,L]

Easily rename your .htaccess file

# rename htaccess files AccessFileName ht.access

Make your wp-login.php page xenophobic

HeHere’she code that you should copy-paste to your root .htaccess file (where wp-login.php exist).

# Redirect wp-admin and wp-login to specified address if not from specific ip
# Btw you're free to add additional directory as you see fit
# Note: This'll break your site if you have plugins/themes that depend on accessing admin-ajax.php
RewriteCond %{REQUEST_URI} wp-login|wp-admin
RewriteCond %{REMOTE_ADDR} !^123.456.789.
RewriteRule . [R,L]

# Or .. if you prefer to return 404 Not found instead of redirecting it, use below code instead
RewriteCond %{REQUEST_URI} wp-login.php|wp-admin
RewriteCond %{REMOTE_ADDR} !^123.456.789.
RewriteRule . - [R=404,L]

Require password for one file

<Files login.php>
   AuthName "Prompt"
   AuthType Basic
   AuthUserFile /home/
   Require valid-user

Protect multiple files

<FilesMatch "^(exec|env|doit|phpinfo|w)\.*$">
   AuthName "Development"
   AuthUserFile /.htpasswd
   AuthType basic
   Require valid-user

Speed up a site by compressing & caching content with .htaccess

In the following series, you can compress and cache your site content with Apache and .htaccess file.

Compress text files

<ifModule mod_deflate.c>
  <filesMatch "\.(css|js|x?html?|php)$">
    SetOutputFilter DEFLATE
Expire headers

<ifModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType image/x-icon "access plus 2592000 seconds"
  ExpiresByType image/jpeg "access plus 2592000 seconds"
  ExpiresByType image/png "access plus 2592000 seconds"
  ExpiresByType image/gif "access plus 2592000 seconds"
  ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
  ExpiresByType text/css "access plus 604800 seconds"
  ExpiresByType text/javascript "access plus 216000 seconds"
  ExpiresByType application/javascript "access plus 216000 seconds"
  ExpiresByType application/x-javascript "access plus 216000 seconds"
  ExpiresByType text/html "access plus 600 seconds"
  ExpiresByType application/xhtml+xml "access plus 600 seconds"
Cache-control headers

<ifModule mod_headers.c>
  <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
    Header set Cache-Control "max-age=2592000, public"
  <filesMatch "\.(css)$">
    Header set Cache-Control "max-age=604800, public"
  <filesMatch "\.(js)$">
    Header set Cache-Control "max-age=216000, private"
  <filesMatch "\.(x?html?|php)$">
    Header set Cache-Control "max-age=600, private, must-revalidate"
Turn etags off

<ifModule mod_headers.c>
  Header unset ETag
FileETag None
Remove last-modified header

<ifModule mod_headers.c>
  Header unset Last-Modified

Performance Optimizer Plugin for WordPress

The plugin will help you increase the performance of your WordPress website. We aim to do this by optimizing critical features of the website’s loading process, thus increasing the loading speed and limiting the bandwidth consumption.

.htaccess Builder

htaccess Builder

To quickly and effortlessly deliver a .htaccess file without having to remember anything about the Apache server language used to construct the .htaccess file!

.htaccess Builder! is complete as is – however – depending on requests and sales, it has the potential to grow to cover just about every function of .htaccess.

  1. Hi! I read your blog you best examples in it. i am sure people will understand the whole steps for How to secure website through .htaccess file. Thanks for sharing!

  2. Hi Noor,

    Indeed a great list of common WordPress security mistakes.

    A couple of days back I faced a situation where there were some unwanted ads being displayed on my blog and that was something I did not install. When inspected I found that there was a lot of unwanted codes that were injected into the WordPress theme files and other main files.

    On further inspection I found out the following 3 things which were the reasons for this:

    1). Not updating the other WordPress installation, plugins, and themes that are being run from the same hosting account if you are using a shared hosting.
    2). Optimizepress 1.0 is known to have a security issue and they have released an update to it. This doesn’t update in the normal updates from your WordPress dashboard. You might want to update it manually if you haven’t done it yet.

    3). Not Cleaning and optimizing your database periodically

    4). Leaving the default themes like twentyeleven etc. as it is and not updating them. This primarily happens if you are using a different theme and these default themes just remain there.

    5). Not uninstalling plugins that haven’t been updated for a long time by its creators.

    These are prone to attacks. A couple of solutions that I found was installing a plugin like Wordfence or, BulletProof Security or, Better WP security.

Leave a Reply

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

You May Also Like