Skip to main content
WordPress made easy with the drag & drop Total WordPress Theme!Learn More

Best .htaccess Snippets to Improve WordPress Security

Last updated on:

WordPress security is one of the most undermined factors amongst novice bloggers. In an unsupervised WordPress installation, there are quite a few potential vulnerabilities that are left unattended. Most of the WordPress installation tutorials explain a quick and easy way to deploy WordPress in minutes. But they miss out a few important security factors. For example, directory browsing and using the ‘admin’ username are considered serious security loopholes. Today we’re going to take a look at 10 .htaccess code snippets which will help improve your WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file.

What is the .htaccess file?

An htaccess file is an optional configuration file for the Apache web server to interpret, for each directory. You can store various settings in that file such as: password protect a directory, block IPs, block a file or folder from public access, etc. Traditionally, the .htaccess file is present in the base WordPress installation directory. It stores the permalink structure by default.

TIP: Before you start with the tutorial, make sure to backup the current .htaccess file (if present) in a cloud storage service like Dropbox. This is to roll back to the last known working .htaccess file, if a certain code snippet breaks your site. Let’s begin.

1. Block Bad Bots

bad bots

One of the best uses of the .htaccess file is its ability to deny multiple IP addresses from accessing your site. This is useful when blocking known spammers and other origins of suspicious or malicious access. The code is:

# Block one or more IP address.
# Replace IP_ADDRESS_* with the IP you want to block

<Limit GET POST>
order allow,deny
deny from IP_ADDRESS_1
deny from IP_ADDRESS_2
allow from all
</Limit>

Where IP_ADDRESS_1 is the first IP you want to prevent from accessing your site. You can add as many IPs you want. No matter what user agents (browsers) 0these IP addresses use, they won’t be able to access a single file from your server. The webserver will automatically deny all access.

2. Disable Directory Browsing

wordpress htaccess hack disable directory browsing

This is one of the most undermined security flaws in a WordPress site. By default, the Apache webserver enables directory browsing. This means that all files and folders inside the root directory (sometimes called the home directory) of the webserver is enlist able and accessible by a visitor. You do not want that because you don’t want people browsing through your media uploads or your theme or plugin files.

If at random I pick 10 personal or business websites running WordPress, 6-8 of them won’t have directory browsing disabled. This allows anyone to easily sniff around the wp-content/uploads folder or any other directory which doesn’t have the default index.php file. In fact, the screenshot you see is from one of my client’s site, before I recommended the fix. Code snippet to disable directory browsing:

# Disable directory browsing
Options All -Indexes

3. Allow Only Selected Files from wp-content

shutterstock_108312266

As you know the wp-content folder contains the most your themes, plugins and all media uploads. You certainly don’t want people to access it without restrictions. In addition to disabling directory browsing, you can also deny access of all file types, save a few. In essence, you can selectively unblock files like JPG, PDF, DOCX, CSS, JS, etc. and deny from the rest. To do this, paste this code snippet in your .htaccess file:

# Disable access to all file types except the following
Order deny,allow
Deny from all
<Files ~ ".(xml|css|js|jpe?g|png|gif|pdf|docx|rtf|odf|zip|rar)$">
Allow from all
</Files>

You must create a new .htaccess file with the code and paste it in the wp-content folder. Don’t place this in the base installation directory – else it won’t work. You can also add any file type to the list by appending a ‘|’ after ‘rar’. The above list contains the necessary files – XML, CSS and JavaScript, common image and document formats and finally the most-used archive formats.

4. Restrict All Access to wp-includes

shutterstock_135573032

The wp-includes folder contains only the files that are strictly necessary to run the core version of WordPress – one without any plugins or themes. Remember, the default theme still resides in the wp-content/theme directory. Thus, no visitor (including you) should require access to content of the wp-include folder. You can disable access using this following code snippet:

# Block wp-includes folder and files
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ - [F,L]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L]
RewriteRule ^wp-includes/theme-compat/ - [F,L]
</IfModule>

5. Allow only Selected IP Addresses to Access wp-admin

shutterstock_140373169

The wp-admin folder contains the files required to run the WordPress dashboard. In most cases, your visitors don’t need access to the WordPress dashboard, unless they want to register an account. A good security measure is to enable only a few selected IP addresses to access the wp-admin folder. You can allow the IPs of the people who need access to the WordPress dashboard – editors, contributors and other admins. This code snippet allows only fixed IPs to access the wp-admin folder and denies access to the rest of the world.

# Limit logins and admin by IP
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 302.143.54.102
allow from IP_ADDRESS_2
</Limit>

Make sure that you create a new .htaccess file and paste it in the wp-admin folder and not the base installation directory. If it’s the latter, no one except you will be able to browse you site – not even search engines! You certainly do not want that. A couple of downfalls of this measure is as follows:

  • If your site allows or promotes new user registration, it would be nearly impossible to keep track of the number of users. For example at WPExplorer, if you want to download our awesome free themes, then you have to register.
  • People with dynamic IP addresses (mostly ADSL broadband users using PPP or PPPoE protocols) have their IPs changed, every time they logout and login to their ISP. Certainly it would be impractical to keep track of all these IPs and add them to the htaccess file.
  • Mobile broadband: Whether you’re on 3G or 4G, your IP address depends on current cell tower you’re connected to. Say you’re travelling – your IP will be constantly changing with every couple of miles you move from the origin. Again, keeping track for the htaccess file is nearly impossible.
  • Public Wi-Fi Hotspots: Using credentials when connected to the Internet using a public Wi-Fi hotspot is a big no-no, since a kid with a tiny software can extract every character you type. Not to mention, each Wi-Fi hotspot will have a unique IP address.

Thankfully, all these disadvantages (save the first one), can be rectified by using a VPN. If you set your VPN to connect using only a single IP address, then you can just add it to your htaccess file, and all your problems will be solved.

6. Protect wp-config.php and .htaccess from everyone

wordpress-ecommerce-security-shopping-tips

The wp-config.php file contains the most sensitive access credentials of your WordPress site. It contains the database name and access credentials and various other critical data, amongst other settings. Under no circumstances do you want other people looking into this file. And of course, you want to disable public access to the source of all this security – the .htaccess file itself. You can disable access to wp-config.php with this following code:

# Deny access to wp-config.php file
<files wp-config.php>
order allow,deny
deny from all
</files>

To deny access to all htaccess files (remember some may reside in the wp-admin and other folders), use this code snippet:

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

7. Deny Image Hotlinking

image-hotlinking

One of the coolest .htaccess file hacks, this one sends content scrapers running with their tail between their legs. When someone uses your site’s image, your bandwidth is being consumed and most of the time, you’re not even credited for it. This code snippet eliminates that problem and sends this image when a hotlink is detected.

# Prevent image hotlinking script. Replace last URL with any image link you want.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourwebsite.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourotherwebsite.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ http://i.imgur.com/MlQAH71.jpg [NC,R,L]

8. Enable Browser Caching

list of web browsers

Also known as client-side caching, this .htaccess hack with enable the recommended browser caching options for your WordPress site. You could also use it in other projects – HTML sites, etc.

# Setup browser caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>

9. Redirect to a Maintenance page

shutterstock_93288208

When you’re migrating webhosts or performing some maintenance task, it is always recommended to create a static “down for maintenance” HTML file to inform your visitors that the website is undergoing an upgrade or maintenance operation. Simply create a maintenance.html file (or any other filename) and upload it to the base WordPress installation directory. Paste the following snippet in your .htaccess file. Once the operation is over, make sure to delete or comment out these lines to go back to overall operation. You can comment out by appending a ‘#’ at the beginning of each line.

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

10. Custom Error Pages

404 template

You can also the .htaccess file to configure user-friendly custom error pages for errors such as 403, 404 and 500. Once you have prepared your error page – let’s say error.html, upload it to your base WordPress installation directory. Then add the following code snippet to your .htaccess file to enable the custom error page:

# Custom error page for error 403, 404 and 500
ErrorDocument 404 /error.html
ErrorDocument 403 /error.html
ErrorDocument 500 /error.html

Conclusion:

Today we’ve learnt some of the coolest htaccess hacks to strengthen your WordPress site. I would suggest you to try out each module one by one while taking a backup of the .htaccess file before and after testing each module. This is because the .htaccess file is very critical. A missing ‘#’ character or misplaced ‘</IfModule>’ could destroy your site’s integrity. If you access your WordPress dashboard frequently on-the-go, it’s recommended not to enable selective IPs to your wp-admin folder.

Over to you – what’s your take on this post? Do you think this is worth the trouble of editing the htaccess file? Do you know of a better security tip? We’d love to hear from you.

htaccess-wordpress-security
Article by Sourav WPExplorer.com guest author
Subscribe to the Newsletter

Get our latest news, tutorials, guides, tips & deals delivered to your inbox.

53 Comments

  1. Anant Shrivastava

    Multiple other simmilar HTACCESS tricks could be found here https://github.com/anantshri/wp-security/ along with htaccess there are multiple functions.php code snippets that can enhance your overall wordpress security.

    P.S. :I am the owner of this github repository and if its missing any reference you are welcome to add references or add suggestions.

    • AJ Clarke

      Nice, thanks for sharing Anant!

    • Alex

      You’ve made a great job with this article! Thanks for the info you’ve shared!
      Can I suggest to make an article with best WP configuration for ROBOTS.TXT?

      • AJ Clarke

        Good idea, thanks for the suggestion Alex.

  2. Thomas

    Thee are all great tricks. I use the protect the wp-config trick on all my sites as well as client sites. I never knew about the wp-includes trick. That one looks especially useful so I am going to try that one. You never can have too many safeguards in place.

    Thanks for the tips 😉

  3. J.Duncan - Paperless Creations

    I have noticed that with cloudflare on our specific settings, that it will not let someone log into wp-admin. You have to put it into development mode to be able to login. Neat little security trick that requires no htaccess changes.

    Great little article! Thanks!

  4. Loc Rabbirt

    Thanks for share 🙂

    Great article !!!

  5. bobby

    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?

    • AJ Clarke

      To be honest I’m not really certain, maybe someone else knows!

  6. rossgile

    Great article.

    I created the following snippet to block those readme’s, wp-config-sample, ini files, etc:

    # BLOCK CERTAIN FILES FROM SNOOPING VERSION NUMBERS, ETC.

    Order deny,allow
    Deny from all

  7. Kristo

    Great Articles. Thank you very much for useful post about WordPress Security.

  8. Amy Brown

    This is a great help to secure a WordPress website from spam. It will help to improve WordPress blogs security.

  9. Rinku Y

    These tips haled me to make my WordPress website secure.

    Thank you Sourav for sharing your knowledge

  10. Elijah

    You are awesome! Thank you so much I was looking for a way to Disable Directory Browsing.

  11. Jack

    Great job, already use the .htaccess and wp-config codes but also want to cover other directories and other WordPress files thanks for making this available.

  12. Pranay

    Hey Sourav,

    Great list of .htaccess snippets. I really loved them, would really go into implementing a few of them. But I’ve been looking for a certain code for the .htaccess file that will allow me to redirect the non-www version of my site to the www one. Can you please help me out?

    Thanks in advance

    • AJ Clarke

      Hum,

      A lot of the managed WordPress hosts have that ability built-in (to redirect non www to www and vise-versa) can you check?

  13. bill

    Nice article.
    Thanks!!

  14. joseph

    thanks buddy for the security article it was so helpful

  15. wpawlowsky

    Thank you for sharing your experience with us. Saved me a lot of headaches.

  16. Piet Rietveld

    Just started using wordpress. Security is very important so I was reading your post with great interest. The question I do have is: where to put the snippets like “disable directory browsing”, “Restrict all access to wp-includes”, etc? In the .htaccess file in the root or create .htaccess for each directory?

    • AJ Clarke

      All the snippets on this post are for your .htaccess file. But if you aren’t sure what you are doing maybe hire a professional to help out because you can really mess things up if you edit this file incorrectly.

      • Deepak

        Thats is not a very nice answer. The above commenter clearly was asking where the .htaccess snippets went – whether the root or the wp-* folders underneath it. AJ Clarke, your answer is not helpful because you’re not answering what was asked and instead are selling something else.

        • Kyla

          We’re not selling anything or being “mean” – we’re simply providing advice 🙂 In our opinion it’s a bad idea for WordPress newbies to be trying out snippets. If you’re not a developer you run the risk of breaking your website which is why we always recommend inexperienced coders hire a professional.

    • Deepak

      Piet, the way the script is written, it has to be in the root www .htaccess file.

  17. Lisa Doucet

    Thank. you. so much 🙂

  18. adamo

    hi.. thx for great tips.. one of my friends wordpress site gets a lot of spam and bots connections.. i did a lot of jobs to protect and secure the site.. so bots don’t publish the comment but they still consume server resources.. i also rename post-comments.php to different one and let the original file empty.. but in logs i still see a lot of connection to this empty file.. so i want to ask if i can block all connections to this wp-comments-post.php file from htaccess.. thanks a lot 🙂

  19. Joel Lukacher

    You didn’t mention security plugins like WordFence. The free version is very good. The premium version is excellent! It makes the security edits to htacess simple. What’s your take on WordFence?

    • Kyla

      Ah but this article is about .htaccess snippets 🙂 We do talk about WordFence, iThemes Security and other options on the blog just in other posts. Checkout our WordPress Security guide to see more!

  20. Johan

    Would the order of these snippets matter for security?

    • AJ Clarke

      Nope 😉

  21. Jim

    Great tips for improving the WordPress security. I have a VPS at rosehosting[dot]com and I contacted the technical support about tweaking the security of my WordPress site. They highly recommended the WordFence plugin. Thanks.

  22. Kaushal Patel

    Great tips on wordpress security through .htaccess file. As wordpress is very prone to get hacked, it is very important to have proper security measures for your website. Thanks

  23. tareq

    thanks , really helpful stuff

  24. baguzInfomedia

    great article. but i need to know how to make wp-login.php blocked

    Thanks,
    baguz infomedia

  25. Panos

    thanks, great article

  26. Edison

    Great. It reduce CPU usage

  27. Full Version Forever

    So if we disable uploaded from indexing then how google will get our images?, or other files that are uploaded. i think when google index our page or post. so all the post images or other file will not be appear so that’s way its a bad impact on seo. but security is most important factor. so what is other best solution that hacker not get access to our uploads, ?

    • AJ Clarke

      I could be wrong but doesn’t the .htaccess snippet only prevent direct access to the image but it’s still “crawlable” by bots?

  28. val caro

    when i implemented this:

    font awesome is not working anymore.. what is the filename extension of bootstrap’s fontawesome? any recommendations/ suggestions? thanks

    • AJ Clarke

      For the code that says “Disable access to all file types except the following” you will have to edit it to allow for the custom font-face mime types. Here is an example from our Total theme docs.

  29. Sandeep Reddy

    Awesome! Thanks Man 😉

  30. Syam Trekker

    Thank you for best tutorial

  31. R.Renjith

    great… thanks man

  32. Julia

    Thank you so much for sharing and creating

  33. Sklnk7

    DO NOT restrict wp-admin to only one IP address, if you do any plugin ir theme that uses Ajax on the front end will break.

    Your users will yell at you your site isn’t working, yet for you, because you’ve whitelisted you’re IP, the site will work perfectly.

    • Kyla

      That is correct – we’ll add a note that users shouldn’t use this snippet if their theme/plugins utilize ajax, or update the snippet to exclude the ajax file.

  34. App Inlet

    Thanks guys, works perfectly!

  35. Michael

    I used tip no. 7 and now it says on my own page that I’ve stolen most of the pics. Which is not true. I deleted the snippet and made a recovery of all. But it is still there 🙁
    I also cleared the cache.

    How can that be?

    • Michael

      Solved 🙂

  36. Charles

    Awesome. It’s great but I’d like a complete SINGLE .htaccess code snippet adding every one of the recommendations in this post!

  37. Israel Mwalyaje

    Good article for security purposes, thanks for sharing it.
    Regards
    Israel

  38. Aldo

    Excellent share and clean easy instructions!!!!

Leave a Reply

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

Learn how your comment data is processed by viewing our privacy policy here.