Posted on

Hardening WordPress: Security through htaccess

WordPress Security htaccess

The WordPress world is panicking. A lot of security breaches have been reported recently and it is important to take every precaution not to become the next website on the 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 htaccess 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 limiting file access.

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

  • Edit it using WordPress SEO plugin by Yoast
  • Edit it using FTP

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 you, as a website owner, deserve.

Prevention is often the best cure.

note: Making changes to htaccess should be a 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.

Security, as everything in life, ultimately comes down to user behavior – avoiding risky situations, avoiding untrusted hosting companies and weak passwords, always using plugins developed with WordPress best practices in mind, installing WordPress security plugins, updating your software regularly, etc. You can read more in our Security of Your WordPress Website article.


If you need help hardening your WordPress website, a website audit is the right thing to do. Get in touch with us and secure your online presence.

Free Marketing Updates
Get the best marketing practices in your inbox.
We always respect your privacy.

Share
Dragan Nikolic
I am a co-founder and editor at ThematoSoup, sharing marketing best practices, tips on how to simplify your online business and make it more manageable.
Dragan Nikolic
Hey @tj_reinhart do you accept new affiliate partners on Sumo? - 5 years ago
Dragan Nikolic

91 comments Hardening 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. Dragan, with the growing popularity of svg images, you should include that in the list of files allowed access to in the /wp-content code

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

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

  18. Pingback: Problems Hardening Security With .htaccess | Chou Seh-fu Blog – Public
  19. Pingback: WordPress Security Plugins - Mt Shasta Design
  20. Pingback: Security Plugins: More of a Problem Than a Solution? | Site Restore NowSite Restore Now
  21. Pingback: 10 Wordpress Security Tips for Your Site
  22. Pingback: Hardening en WordPress |
  23. I really like it when people come together and share ideas.

    Great website, continue the good work!

  24. Pingback: 通过.htaccess文件保护WordPress网站 - 五维空间
  25. Regarding protecting Wp-Content directory… will the htaccess file your recommend creating for in the wp-content directory (which would restrict access to only pretty much images and similar content), will it cause problems with the new WP automatic updates/upgrades?

    I ask because WP uses a subfolder underneath Wp-content directory called “upgrades” and since htaccess protects subfolders, I wonder whether this would cause update/upgrades failures/problems? By following this advice, wouldn’t WP itself have a problem using that subdirectory as a temp upgrade location?

    1. Bobby,

      That’s a valid question and since we’ve moved to a hosting that doesn’t allow any playing around with .htaccess I cannot test it. But, I’ve tested every little .htaccess snippet at the time of writing this article and had zero problems updating WordpPress, although I’m not sure about automatic updates.

      I hope someone will share the experience.

  26. Pingback: WordPress Security Tips « Web Host
  27. This is really great, thank you!

    I have a question, would any of this cause the PDF’S on my site to return a 403 error? I noticed that now my PDF’S are doing that…or is there part of that code that I can edit so that it does not affect my PDF’s??

    Maybe that’s not what’s causing it but I noticed it right after adding that code in; ps just FYI I did reset my file permissions too…

    THANK YOU ahead of time!

  28. I fixed my issue with the PDF’S I had to add pdf to the .htaccess file you suggested for the wp-content:

    ‘order deny,allow
    deny from all

    allow from all

    1. Sorry that was supposed to be: I had to add the following to the wp-content to fix my issue with the PDF files not working correctly!

      order deny,allow
      deny from all

      allow from all

  29. Is there any way that any of the code you suggested might affect the Visual Editor to go ‘blank’? The html tab works fine but now my visual editor isn’t working… might any of the code I added affect that?

    Thank you!

  30. Hmm it seems ike your site ate my first comment (it
    was extremely long) soo I guess I’ll just sum it up what I wrote and say, I’m
    thoroughly enjoying your blog. I as well am aan aspiring blog writer but I’m still new to the whol thing.

    Do you have any helpful hints for beginner blog writers? I’d definitely appreciiate it.

  31. Thanks so much for the link to your informative article about securing WordPress the right way. There are some great and useful resources. Glad I came across your site.
    Thanks!

  32. Just curious, I added the separate .htaccess file in my wp-content folder on a certain site and it’s blocking Google Search Console from seeing my sitemap…is that odd? Any thoughts on this would be great!

  33. Hi and welcome to my blog . I’m Kelsie Davenport.
    I have always dreamed of being a novelist but never dreamed I’d make a career of it. In college, though, I helped a fellow student who needed help. She could not stop complimenting me . Word got around and someone asked me for writing help just a week later. This time they would pay me for my work.
    During the summer, I started doing research papers for students at the local college. It helped me have fun that summer and even funded some of my college tuition. Today, I still offer my research paper writing to students.

    Academic Writer – Kelsie Davenport – supportthedandelionschool.com Corps

    1. WebCoders is a leading WordPress development company. They have some of the most experienced and knowledgeable developers in the team who are aware of each and every aspect of WordPress. You can rely on the services offered by them and you can rest assured that you will get the best value for your hard-earned money. They offer some additional services such as SEO (Search Engine Optimization), CMS solutions, E-commerce web solutions and so on. For more details, visit webcoders.co. Hire the best WordPress Developer here.

  34. In order to have a professional look at your feature-rich site or blog, it is your discretion choosing the outsourcing of Custom WordPress Development to different expert vendors. Highly trained and qualified, experienced developers can access the latest tool and technology for developing blogs and websites on this very platform. Experts usually work closely along with the specialized custom WordPress development experts of the organization for the process of customizing the design following one’s specific business requirements.
    Custom WordPress Development

  35. WordPress has become the facto for developing Content Management System. We offer a complete Custom WordPress Development Company service to our esteemed clients. Our WordPress development is having virtually 3 different parts which consist, Presentation Layer, Logic Layer, and Data Layer.

  36. WordPress has become the facto for developing Content Management System. We offer a complete Custom WordPress Development Company service to our esteemed clients. Our WordPress development is having virtually 3 different parts which consist, Presentation Layer, Logic Layer, and Data Layer.
    Custom WordPress Development Company

  37. so, i need to put all the code in the htaccess file in the root, before # END WordPress??

  38. Web development companies in Pakistan use a variety of web development frameworks and tools to build websites. Some of the most commonly used frameworks include PHP, Laravel, CodeIgniter, and Ruby on Rails.

  39. In response to the recent surge in WordPress security breaches, implementing robust security measures is paramount. Utilizing the .htaccess file can significantly enhance protection. Perform a thorough review of this degree of hardening, focusing on strong access controls, and keep abreast of evolving security best practices to safeguard your WordPress site effectively.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.