WordPress Security Through .htaccess

WordPress world is panicking. A lot of security breaches have been reported recently and it is important to take every precaution not become the next website on hackers’ list. It’s up to you to make your WordPress as secure as possible and minimize the risk of spending hours on the phone with your hosting company, trying to get your credentials back.

There are several ways of making your WordPress secure (using WordPress best practices, security plugins, content delivery networks…) and configuring your .htaccess is just one of them, the one that belongs to the domain of prevention.

Configuring .htaccess

.htacess is a configuration file that allows you to override your server’s global settings for the directory that it’s in, by limitting file access.

There’s a couple of ways you can access it:

  • Find it in the root of your website
  • Edit it using WordPress SEO plugin by Yoast

Here’s a piece of code generated by WordPress and you’ll find it in almost every .htaccess file:

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

Anything else you decide to apply to harden WordPress security should be added after this.

Protect wp-config.php

WordPress best practices suggest you protect your wp-config.php file and you can do that by adding:

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

Prevent Directory Browsing

You know how you can change a few characters in a URL and continue browsing the website. With this code you’ll prevent any directory browsing:

# directory browsing
Options All -Indexes

Disable any Hotlinking

Sometimes other (non-ethical) site curators will try to use your images and videos and put a strain on your serves, which uses your disk space and bandwidth. While this is not in the domain of WordPress security, it will certainly help your website’s overall health. Adding this to your .htaccess will prevent hotlinking from happening:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?YourDomain [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

note: Be sure to change “YourDomain” with your domain address and leave out the “www” part

If you need to allow certain websites to use your images, then you can use this online tool for generating the anti hotlinking code where you can define various parameters.

Protect /wp-content Directory

WordPress holds all your media files in here and they’re an asset you want search engines to crawl. But, “/wp-content” is a place where your themes and plugins reside, too. You don’t want to allow access to those sensitive .php files.

In order to work you need to create a separate .htaccess file (just use your FTP client and create a file with no name and give it an “.htaccess” extension) and put it in your /wp-content directory. This code will allow access to images, CSS, java-script and XML files, but deny it for any other type.

order deny,allow
deny from all
<files ~ ".(xml|css|jpe?g|png|gif|js)$">
allow from all
</files>

That’s it. Your WordPress website should be a lot safer place now. There’s just one last thing we should do and that’s protecting the .htaccess file(s).

Protect the .htaccess Itself

We’ve done a lot to protect WordPress, but the .htaccess file itself is still open to attacks. The following code snippet will stop anyone from accessing (reading or writing) any file that starts with “hta“.

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

While you can install various WordPress security plugins, sign-up for monitoring services and content delivery networks which filter your traffic, configuring .htaccess file so it strengthens your WordPress security is a good step toward that peace of mind every website owner needs.

Prevention is often the best cure.

note: Making changes to .htaccess should be pretty relaxing job, but if you use plugins (ex. WordPress SEO) for configuring .htaccess, please make sure to also have FTP credentials, just in case you need to directly access and reconfigure it.

Still not convinced you need to act? Why don’t you check out this nice “What if your WordPress gets hacked” infographic.

WordPress Security Infographic by StartBloggingOnline.com

Security, as everything in life, ultimately comes down to user behavior – avoiding risky situations, untrusted hosting companies and weak passwords, always using plugins developed with WordPress best practices in mind, updating your software regularly, etc. You can read more about WordPress security on Search Engine Journal blog.

If you use code snippets other than the ones listed here, feel free to share them with us and don’t forget to sign up for more WordPress tips.

Dragan Nikolic
I am the SEO & social media guy here at ThematoSoup, sharing tips on how to simplify your online business and make it more manageable.
Dragan Nikolic

@NikolicDragan

Co-founder & project manager at @ThematoSoup, interested in #minimalism and #WordPress. In love with nature.
The End of the Day Philosophy http://t.co/6w6PMuQpCh - 2 weeks ago
Dragan Nikolic
Dragan Nikolic

55 thoughts on “WordPress Security Through .htaccess

  1. Great tips! thanks for sharing! The last tip — protecting the .htaccess file itself — where do you put that code? at the top, before the wp code, at the bottom? Don’t want to screw up anything :D

    1. Kimberly, thanks for stopping by. Most of this code should probably go in server configuration file, but that’s not as convenient as configuring .htaccess files.

      The code that protects .htaccess files goes in the .htaccess that sits in your website root directory. It can be added before or after any other code you already have in it.

      1. Thanks, Dragan! I really appreciate you getting back so quickly! The information in this one post is stuff I have been trying to figure out for awhile now and my research endeavors have been less than favorable needless to say! So finding this post in the latest wpmail newsletter just made my day!! And thanks for clarifying about where to put the last bit of code :D

        I’m starting to embrace that I won’t break anything if I tweak the htaccess file. And of course having a backup at all times in case I do screw things up LOL But I am getting much more comfortable and your post totally has helped! Thanks again!

        1. Good to hear that :)

          You won’t break anything, but it’s good to have an FTP access, just in case you can’t access it through WP dashboard, due to changes you make. You can then just delete the stuff you added and everything will get back to normal.

  2. If I have WordPress installed in a subdirectory, do I need to add the name of the subfolder in this code?

    I’d love to know…thanks!!!

    1. Not sure I entirely understand, but I’ll try to explain:

      .htaccess file controls directory it’s in and all respective sub-directories, so you don’t need to enter path, you just decide where you want to have it. For example, if you put it in the root of your website (most common case), every rule in the .htaccess will apply to the whole website.

      This is not the case when you want to deny access to sensitive files only in your /wp-content directory. In this case, you need to create a separate .htaccess file with the rules listed above and put it in the /wp-content directory, so it applies only to that directory and its sub-directories.

      Was this helpful?

      1. Yes, sorry I didn’t wrap the code right. I usually have my WordPress installs in a subdirectory of the web root. I was just curious if I would put the .htaccess file commands you listed above in the root .htaccess file, or if I’d have to make one in the subdirectory that houses the WP files.

        It sounds like I’ll have to put the commands you suggested in a .htaccess access file in the subdirectory that houses my WP core files. Correct? Thanks!

        1. If you’re familiar with configuring your server’s config file, you may even use that for controlling global settings of all your websites and that would save you some time, if you have a lot of websites.

          To answer your question, yes, you can choose to put the file in subdirectory that houses your WP-core files.

  3. I did a similar post on my blog, but the tutorial basically restricts access to WP admin, bar IP addresses defined in the htaccess file, the idea is that the current BotNet scare that targets WP admin by trying to login continuously will not even have a form to attempt logins and then not cause a continuel attack (DDoS esque) also keeping any compromise of your admin area out of reach… In theory.

    http://www.mathewporter.co.uk/secure-wordpress-admin-htaccess/

    1. Mathew,

      Thanks so much for the link to your article, I’ll definitely try IP filtering. Do you think that limiting the number of incorrect logins may also work towards repelling BotNet attacks?

  4. Will any of these tips break plugins like backWPup or any security plugins like wordfence? Or are these pretty safe with plugins?

    1. Hi Robert,

      That’s an excellent question. I’ve just tried both BackWPup and Wordfence and they work as they should. But, if you experience any problems with your WordPress installation you can easily use FTP to access your .htaccess file and delete any custom code.

  5. Must depend on where you put the htaccess file. I modified the one in the wp directory and the hotlinking fix turned off all my images from public view! I’ll play a bit more more later but thanks for these tips.

  6. I have a WordPress blog and I have changed the .htaccess, but the plugin Better WP Security does not work. Can you help me?

    Thanks

  7. You should also deny access to readme.html along with license.txt, so people can’t get access to these files. It also is a good idea to use .htacccess files in other areas of your site to deny php execution such as in wp-includes and the uploads folder. You should also deny access to install.php and upgrade.php in the wp-admin folder.

  8. Hello,

    In case of htaccess file in wp-content I use the rule that’s described in the post. With that, how do I allow certain plugin files to still run?

    I’ve tried this for example:

    Allow from all

    But without any luck, I’m getting 403 Fobbiden.

    I would hugely appreciate your help.

    1. Oh, it didn’t post the htaccess directive correctly.. I was trying Files “plugins/advanced-custom-fields/js/input.php”.

      So I only want to allow access to a specific file using the file path instead of allowing access to all files called “input.php”

      Thank you,
      Dasha

  9. Hi Dasha, thanks for stopping by.

    Could you try adding this to the .htaccess file in you /wp-content directory, beneath the code you already have there -

    <Files input.php>
    Order Allow,Deny
    Allow from all
    </Files>

    1. I’ve just realized that you wanted something else, entirely. You see, all your .js files will be allowed to run if you used the code and put it in the /wp-content .htaccess file. The code allows all xml|css|jpe?g|png|gif|js files to run.

      It must be that something else is blocking it then.

      1. Hello,

        Thank you very much for your replies!

        I think the first reply in nearly there. With the following code in htaccess file in wp-config it means that all files called “input.php” from any plugins are will be allowed to run:

        Order Allow,Deny
        Allow from all

        What I was hoping to do it to allow “input.php” file to run only from a specific plugin, something like:

        Order Allow,Deny
        Allow from all

        However, that didn’t work. I’m not htaccess guru, so I don’t know if it’s wrong syntax or it’s not possible to only allow a specific file access from down the hierarchy from wp-content.

        Does that make sense?
        Dasha

          1. Dasha,

            I’m no expert when it comes to .htaccess or server configurations myself. You could probably ask your hosting company for advice. I’m sure they deal with this kind of things every day.

            My quick fix would be this: You know that .htaccess rules apply to all subfolders. You can add another .htaccess in the plugin folder with the code I’ve given you:

            <Files input.php>
            Order Allow,Deny
            Allow from all
            </Files>

            As for the “invisible code” in your comments, see how I’ve done it https://dl.dropboxusercontent.com/u/7059892/code-sample-in-comments.png

            Hope this helps

  10. This are great & useful resources. It is the first time I have encountered many of these plugins. I have already have 4 plugins installed in my site. I will check which one or two I can add. Glad I came across your site. Many Thanks!

  11. Hi,

    I had the message come up in the BO of WP to say i need to add the code to the .htaccess file, i didnt have one so i created it with:

    RewriteEngine On
    RewriteBase /wordup/
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /wordup/index.php [L]

    What they had said add, i added it to my subfolder with the WP site files but then nothing would load, is there another step to the process, any help would be great.

    PS) great article and illustrations

    Regards

    Patrick

  12. Which code snippet would you prefer to use in order to protect the .htaccess Files?

    Clearly option b is broader, and therefore more protective, which would protect the file if a user changes the filename. However, Option A is nice because it is self-explanatory and could more easily be included in a compiled list of commands.

    # Option A filename must be exact

    Order allow,deny
    Deny from all

    # Option B is broader. Protects any filename that starts with hta

    order allow,deny
    deny from all
    satisfy all

    1. Hi Corbin, thanks for stopping by. I’d choose option B, because you won’t have to think about it later if you choose to change the names of some of the .htaccess files or think about uppercase and lowercase filenames.

  13. The security of the site lies on your hosting company is all true. I’ve encountered this when I hosted my site on company X. My site was compromised with lots of spam links injected at the sites footer. Don’t forget to backup often.

    1. Thanks Faust. Yes, hosting companies with poor security measures tend to be the victims of hacker attacks. Everyone should first do a good research before choosing a hosting company.

  14. Hi Dragan,

    Thanks for sharing to make the worldpress a safe place! ;)

    Trying to Protect /wp-content Directory I realize that I “lose” font-awesome icons, the form captcha (php? using wpcasa contact form theme), and the functionality of the currency converter (ajax? same framework).

    Should I add specific file formats to prevent this or i cannot use this?

    1. Hi Víctor,

      I’m sorry to hear that you have difficulties with some of the the 3rd party plugins and icons. Unfortunately, I haven’t dealt with those in the past, so I’m not able to help you.

  15. Thanks for precious .htaccess tutorial. I really don’t want to install WordPress security plugins. I used to try some plugins before and they totally broke themes which I like much. Do you think it’s OK for WordPress websites by just configuring .htaccess from root and adding .htaccess into wp-config folder? I’m bit scared of using security plugins.

    One thing I don’t understand at “Protect the .htaccess Itself” section – where should I add the code which is mentioned at that section?

    Thanks you very much for this valuable post and look forward to reply.

    1. You can try using Wordfence for securing WordPress. If it breaks your theme, then it’s something with the theme that’s wrong.

      The “protect .htaccess code” should go in the .htaccess file that’s located in the root of your website.

  16. Thank you so much for the article , i have some questions :
    can i have just one .htaccess in the root with all the codes above ?
    should i write the codes exactly after “# END WordPress” ?
    for the wp_ content you have mentioned ” jpe?g ” is the ” ?” correct or its just a bad typing?

    thank you so much again ,

    1. 1. You should have only one .htaccess file. But, for disabling hotlinking, you need a separate .htaccess in your /wp-content directory.

      2. Yes, you can write it anywhere after “#End WordPress”

      3. “jpe?g” covers both jpg & jpeg files, so that’s not bad typing.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>