10
July 31, 2014 Best .htaccess Snippets to Improve WordPress Security wpexplorer.com/htaccess-wordpress-security 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. 1/10

Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

July 31, 2014

Best .htaccess Snippets to Improve WordPress Securitywpexplorer.com/htaccess-wordpress-security

WordPress security is one of the most undermined factors amongst novice bloggers. In anunsupervised WordPress installation, there are quite a few potential vulnerabilities that are leftunattended. Most of the WordPress installation tutorials explain a quick and easy way todeploy 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 yourWordPress blog’s security. Before we get started, let’s take a quick look into what is thehtaccess file.

What is the .htaccess file?An htaccess file is an optional configuration file for the Apache web server to interpret, foreach 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 ispresent in the base WordPress installation directory. It stores the permalink structure bydefault.

1/10

Page 2: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

TIP: Before you start with the tutorial, make sure to backup the current .htaccess file (ifpresent) 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

One of the best uses of the .htaccess file is its ability to deny multiple IP addresses fromaccessing your site. This is useful when blocking known spammers and other origins ofsuspicious 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 canadd 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 automaticallydeny all access.

2/10

Page 3: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

2. Disable Directory Browsing

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

If at random I pick 10 personal or business websites running WordPress, 6-8 of them won’thave 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. Infact, 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

3/10

Page 4: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

As you know the wp-content folder contains the most your themes, plugins and all mediauploads. You certainly don’t want people to access it without restrictions. In addition todisabling directory browsing, you can also deny access of all file types, save a few. Inessence, you can selectively unblock files like JPG, PDF, DOCX, CSS, JS, etc. and deny fromthe 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 filetype 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 archiveformats.

4. Restrict All Access to wp-includes

4/10

Page 5: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

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

# 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

5/10

Page 6: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

The wp-admin folder contains the files required to run the WordPress dashboard. In mostcases, your visitors don’t need access to the WordPress dashboard, unless they want toregister an account. A good security measure is to enable only a few selected IP addresses toaccess the wp-admin folder. You can allow the IPs of the people who need access to theWordPress dashboard – editors, contributors and other admins. This code snippet allows onlyfixed 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 thebase 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 measureis as follows:

If your site allows or promotes new user registration, it would be nearly impossible tokeep track of the number of users. For example at WPExplorer, if you want to downloadour awesome free themes, then you have to register.People with dynamic IP addresses (mostly ADSL broadband users using PPP orPPPoE 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 thehtaccess file.Mobile broadband: Whether you’re on 3G or 4G, your IP address depends on current

6/10

Page 7: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

cell tower you’re connected to. Say you’re travelling – your IP will be constantly changingwith every couple of miles you move from the origin. Again, keeping track for thehtaccess file is nearly impossible.Public Wi-Fi Hotspots: Using credentials when connected to the Internet using a publicWi-Fi hotspot is a big no-no, since a kid with a tiny software can extract every characteryou 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 youset your VPN to connect using only a single IP address, then you can just add it to yourhtaccess file, and all your problems will be solved.

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

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, amongstother settings. Under no circumstances do you want other people looking into this file. And ofcourse, you want to disable public access to the source of all this security – the .htaccess fileitself. 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 otherfolders), use this code snippet:

7/10

Page 8: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

# Deny access to all .htaccess files

<files ~ "^.*\.([Hh][Tt][Aa])">

order allow,deny

deny from all

satisfy all

</files>

7. Deny Image Hotlinking

One of the coolest .htaccess file hacks, this one sends content scrapers running with their tailbetween their legs. When someone uses your site’s image, your bandwidth is being consumedand most of the time, you’re not even credited for it. This code snippet eliminates that problemand 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

8/10

Page 9: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

Also known as client-side caching, this .htaccess hack with enable the recommended browsercaching 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

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

9/10

Page 10: Best .htaccess Snippets to Improve WordPress …...WordPress blog’s security. Before we get started, let’s take a quick look into what is the htaccess file. What is the .htaccess

# 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

You can also the .htaccess file to configure user-friendly custom error pages for errors such as403, 404 and 500. Once you have prepared your error page – let’s say error.html, upload it toyour 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. Iwould suggest you to try out each module one by one while taking a backup of the .htaccessfile before and after testing each module. This is because the .htaccess file is very critical. Amissing ‘#’ character or misplaced ‘</IfModule>’ could destroy your site’s integrity. If youaccess your WordPress dashboard frequently on-the-go, it’s recommended not to enableselective 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 thehtaccess file? Do you know of a better security tip? We’d love to hear from you.

10/10