Protect-the-wp-config.php-File-in-WordPress-Blogs

With the help of .htaccess (hypertext access) file, you can get a directory-level configuration, and it allows you to decentralize the management of your web server configuration. As well it 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, then please grab the WPArena RSS feed for keeping 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 properly. So Always have a Backup.

Protect-the-wp-config.php-File-in-WordPress-Blogs

1. Restrict access to 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 through adding a .htaccess file into a wp-admin directory like:

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

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

By restricting  the directory with a password:

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

2. Individually Blacklist IP Address

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

<Limit GET POST PUT> order allow,deny allow from all deny from 192.168.0.10 </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 a simple way to and many functions, no need any database supported.

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

4. How To Disable Directory Browsing using .htaccess

# disable directory browsing Options All -Indexes

5. Disables image hotlinking

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

6. Redirect WordPress Feeds to Feedburner via .htaccess

.htaccess is a powerful tool which 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.

For those of us using Feedburner for all content and comment feeds, we have consolidated the previous .htaccess code into a single redirect. 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-]+)?/?$ http://feeds.feedburner.com/wordpressarena [R=302,NC,L]
</IfModule>

7. IP Delivery to Stop RSS “Content Thieves”

Quads Zilla at Seo Black Hat explained how to know IP address who is stealing your RSS Feed and how to block IP address through the .htaccess file.

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

8. How to setup maintenance page with the .htaccess file?

You want to migrate your blog, switch themes, or to 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]

9. 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 posting comments on your blog.

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

10. Force “File Save As” Prompt

By using this code you can force user not to open downloadable files instead you force them to save as:

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

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

# CASE SENSITIVE METHOD
<Files.htaccess>
order allow,deny
deny from all
</Files>

Weak pattern matching

# WEAK PATTERN MATCHING
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy All
</Files>

Strong pattern matching

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

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

In order 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 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, then this WP Safer Admin Plugin is the right tool for you!

WP-Restrict

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

13. 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/.*$

14. Removing Category Base from WordPress URLs

The below .htaccess code illustrates two different ways to redirect any request for ./category/slug/ to /slug/ You should only redirect after applying the PHP hacks described earlier. Otherwise, you could end up creating a loop.

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

15. Valiantly automatically fix URL spelling mistakes

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

<IfModule mod_speling.c>
CheckSpelling On
</IfModule>

16. Redirect the spammers where you want

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

# block comment spam by denying access to no-referrer requests
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*wparena.com.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule ^(.*)$ ^http://the-site-where-you-want-to-send-spammers.com/$ [R=301,L]

17. Easily rename your .htaccess file

# rename htaccess files AccessFileName ht.access

18. Make your wp-login.php page xenophobic

Here’s the code that you should be 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 . http://www.domain.com/ [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]

19. Require password for one file

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

20. Protect multiple files

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

21. Speed up your site by compressing and caching your 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
  </filesMatch>
</ifModule>

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"
</ifModule>

Cache-control headers

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

Turn etags off

<ifModule mod_headers.c>
  Header unset ETag
</ifModule>
FileETag None

Remove last-modified header

<ifModule mod_headers.c>
  Header unset Last-Modified
</ifModule>

22. Performance Optimizer Plugin for WordPress

The plugin will help you increase the performance of your WordPress website. We aim to do this by optimizing key 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.

Noor Mustafa Raza

Noor Mustafa Raza

I am a WordPress Developer and Designer, author @WPArena. I am providing Free WordPress consultation and can help you to install WordPress in a secure way to small businesses and bloggers.

Join the Conversation

2 Comments

  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 comment

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