1. Freebies
  2. Advanced Web Design Tutorials
  3. WordPress Htaccess
Wordpress Htaccess - A Wordpress Security Tutorial

Wordpress Htaccess - A Wordpress Security Tutorial

Your WordPress Htaccess is a file you should be taking seriously. It can boost security, performance, and seo without a ton of effort. Take a couple minutes and learn a few WordPress htaccess tricks of the trade.

One aspect that makes WordPress so popular is the carefully curated plugins that are so easily installable. In the case of security though, you don't want cookie cutter... You want bulletproof ...and using htaccess effectively is as bulletproof as it gets. While improving your website's security in just a couple steps, we'll also cover a few easy htaccess additions that can have your website running faster and more efficiently. If you're not already familiar with utilizing these files, you'll be amazed by the functionality they add. If you've got a few years of experience under your belt, hopefully you'll still catch a couple nuggets of code you don't have lying around worth keeping.

Htaccess Invisible

WordPress Security Caveat

If you've got some experience feel free to skip past this part. If you're a relative noob to web security you should digest these brief tips before getting started.

  • Be Careful: Htaccess is a loaded assault rifle. It can be very useful when handled correctly, but don't let your nephew play with it. Make backups, test interactions locally, and for god's sake - Don't test these things out on a live site.
  • It's Invisible: Can't see a file named ".htaccess" on your server? Don't worry, you're not crazy. ...We'll you might be, but that's not the point. Truthfully, I stared at those files named "htaccess.txt" for months before even wondering what they were for (see wiki - .htaccess). Basically, those are unconverted ".htacess" files. All you need to do to convert it is change the filename. Add a period to the beginning of the filename and remove the ".txt" from the end, the file then becomes something your server recognizes as a configuration file. Important Note: Depending on what coding application you're using, you may need to set a preference to "View Invisible Files" - Since that's exactly what adding the first period and stripping the file type does.
  • Keep Your Goal in Mind: Your goal in web security should never really be to grade 100%. That's not realistic and being realistic about that will help you keep perspective. There is quite simply no better security then a recent backup. If a hacker is intent on compromising your site, they will. Accept that and move on. What you really don't want to be is "low hanging fruit" and what you should aim for is having a website that is a headache for a "would be hacker" to access.

Now that you I've said my piece to those of you completely unfamiliar with these concepts, let's move along to illustrating how this one simple file can impact your websites performance so immensely. If you'd like a little more info on htaccess' functionality before getting started, I'd suggest you look over the WordPress' Codex or my favorite post AskApache's Ultimate HTAccess (which has helped me on the topic quite a bit).

Default WordPress Htaccess

WordPress Default HtaccessIf you look on the root of your server, you should either find a file named "htaccess.txt" or ".htaccess". If you can't find either, simply create a new file named ".htaccesss" and include the following chunk of code, which is currently default WordPress htaccess. Make sure you can see the file and check your frontend to ensure everything is functioning as desired.

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

This code looks tricky at first, but it's really not. It's written in RegEx which is short for "Regular Exprerssion" - a slightly different coding language, but very logical once you get the logic (see wiki). The most important lines to note are the first two. These two lines are instructing the server to allow this file to handle rewrites and then setting it's base. Every server is unique - but if you're setting up a subdomain, you'll probably need to change the following lines "RewriteBase /" and "RewriteRule . /index.php [L]" to include your file structure (something like "RewriteBase /subfolder/" and "RewriteRule . /subfolder/index.php [L]"). You may need to make additional adjustments, but 95% of the servers I've worked on will function as is or with that small addition.

Wordpress Htaccess Security Additions

Now for the fun stuff. Keep in mind some of these rules need to be in a specific order. You can run into problems if you're rewriting a lot. Just remember that you want to use the least amount of code & redirects possible to get all the url's where you want. Use a little common sense and consider if a particular rule is dependent or independent of a given process. Also keep in mind that the default chunk is a simple rewrite you'll want to keep. It's basically removing the "index.php" that usually appears at the end of a url. Keep that where it is and do most of your customization after. Restricting access is the only function you'd really want to place before the default code.

Temporarily Closed

This rule needs to have the comments stripped (which just means removing the hashtag at the beginning of each line), but this is VERY handy to include in your website for development. Simply plug in your current IP and your site will only be accessible to that exact IP... meaning only your ip should be able to see it. If you don't know your current IP, ArulJohn will tell you pretty quickly. The usefulness of this snippet should be apparent, but not only does it block every other IP out of your site it also returns a 503 Error. This tells both bots and visitors that this is a temporary outage and you can obviously customize the message to your liking. I recommend keeping this code snippit at the top of every htaccess file.

# ErrorDocument 503 "Our website is temporarily closed for scheduled maintenance."
# RewriteEngine On
# RewriteCond %{REMOTE_ADDR} !^555\.555\.555\.555$
# RewriteRule .* - [R=503,L]

Block Htaccess Reading

Depending on how your permissions are setup, a visitor could actually read your htaccess with a little know-how. This snippet prevents that from happening by denying all visitors to that file name. Logically it directs the server to look for a filetype that starts with ".hta" and denies the ability to view it (check out the first line). Additionally - I'd recommend removing the file actually named "htaccess.txt" if it's still there. Keeping an easy to see duplicate may be helpful for you, but you could be providing a map to intruders.

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

Deny Config Files

Similarly to the previous htaccess blocking rule, there is really no good reason a visitor should be able to see any "wp-config" files. This snippet will provide that access block.

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

Restrict Access to WP-Admin

Unlike the previous rules, this will actually require that you create another htaccess file. Since htaccess rules apply to it's folder level and everything below, including this additional htaccess file in your "wp-admin" folder will block access from everyone besides the IP you include. This redirect is not as "friendly" as the "Temporarily Closed" rule, but it does the trick and will deny access to anyone but you. If you need to include more then one IP (home and office for example), simply copy the line "allow from..." and paste it directly after. This code can also be useful for restricting access while in development, just include a clients IP and your own - then only you two have access.

order deny,allow
deny from all
allow from 555.555.555.555

Restrict Access to WP-Content

Another area that visitors have no need to snoop around is your "wp-content" folder. Really, all the data they need to access are the xmls, images, and css. That's exactly what this rule does. It begins by denying everything, then allows the files I previously mentioned. This rule should be included in it's own htaccess file which should be located in the "wp-content" folder, just like with the previous rule.

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

Wordpress Htaccess Performance Additions

Remove WWW

A basic SEO rule is to ensure you're not providing duplicate content. If you can access your site with and without a "www." at the beginning, you've got a serious problem. This snippet fixes that issue with no need for fancy SEO plugins.

RewriteCond %{HTTP_HOST} !^yourdomain.com$ [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} !^\.yourdomain\.com$ [NC]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

301 Redirects

Any page that has ANY value whatsoever should be considered on your website. If it moves or you want to remove it altogether, make sure to provide a 301 redirect so traffic coming to that page goes somewhere useful and doesn't end up on a 404 Error page. These rules must be after the "rebase" line of the default htaccess and I personally think they belong towards the end of your file (of course, rule order depends on a lot of factors). Want to make sure it's working? Just go to the url you're attempting to move and it should quickly bounce to exactly where you want it to go.

Redirect 301 /oldpage http://yourdomain.com/newpage

Need to change the urls of a whole folder? RegEx let's you specify one pretty easily. Just keep in mind that moving a group is more complicated then moving just one file.Too many folder redirects can get messy.

Redirect 301 /oldfolder/* http://yourdomain.com/newfolder/*

Need to remove a string? I've had several clients that formerly had mobile sites that were identifiable by "?mobile" at the end of the url. When they went to responsive websites, they needed those old mobile pages to redirect (to keep the "juice" of the previously crawled urls). This tactic uses a condition to look for the query string ("?mobile"), then applies a rule that strips it.

RewriteCond %{QUERY_STRING} ^(.*&.)?mobile=*
RewriteRule ^(.*)$ $1?%1 [R=301,L]

Add Expires

Expires provide a method of telling servers the "shelf-life" of a particular file. This is a method which I'm sure isn't perfect in terms of efficiency... so if you're an expert please feel free to comment below. That said - I think this snippet is pretty solid. It specifies which files will receive the expires, then applies it directly. If you want to get down to providing different files a different "shelf life", this post on Tips and Tricks should help you out. As a general rule though, this gives your files the expires that a server hopes to see. It's an aspect you won't notice unless looking closely at a files detail, but it's something that servers want to see and I don't see that going away for quite some time.

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 10 days"
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType text/plain "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-icon "access plus 1 year"

Font Based Icon Error

If you use font based icons and getting problems with a cdn, your issue is most likely that your access control isn’t allowed. That can be remedied with the following code...

<FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"

Want to Keep Tuning Your Performance?

I created a post a while ago pointing out a few valuable testing resources, you can check it out here Free Site Ranking Utilities. I'd also recommend that you try the links below to become an expert on the topic of WordPress htaccess. Also note that htaccess functions on the server level, so although the application may be a little different htaccess can be a useful addition to any of your websites.

Hopefully you've found this post useful and if you're a complete stranger to utilizing htaccess, I'm giving you a virtual high five because you're adding a huge weapon to your arsenal. Check out the video below and feel free to leave any additional tips, questions, or comments you may have below.

Related Articles
  • 10 Top CDN Plugins, Providers, and Tips
    If you’re minding your pageload times, then your probably already familiar with CDNs. We’ve collected the top cdn plugins, quality cdn providers, and a few tips for handling cdn on cms.
    10 Top CDN Plugins, Providers, and Tips
  • Dropbox Database Sync for MySQL & MAMP
    Using Dropbox for web development is an easy way to share files across multiple local servers. This tutorial shows you how to setup a Dropbox database sync so you can trigger your MySQL database sync in the push of a button.
    Dropbox Database Sync for MySQL & MAMP
Written By:
Matthew Haeck
Raleigh, NC

Greetings, I'm the lead designer and resident full stack web developer at Haeck Design. A majority of my time is spent creating beautiful logos, websites, print design, & staying up to date on all the tricks of the web development trade.

Haeck Design - Stamp Logo