14 Best .htaccess Snippets for WordPress

A .htaccess file is a distributed Apache server configuration file in which you can give commands to your server about how to serve your website. It can be used for many different kinds of configuration, such as security settings, directory protection, pretty permalinks, redirecting and rewriting URLs, and others.

The main .htaccess file can be found in your root directory, inside the public_html folder on live servers. However, it’s possible to set up a .htaccess file inside other directories as well. For instance, adding a .htaccess to the wp-admin folder is a common security solution used by popular security plugins such as BulletProof Security

Default .htaccess for WordPress

Every WordPress install comes with a default .htaccess file you can find in your root directory. The file is generated when you enable Pretty Permalinks for your WordPress site. The default .htaccess looks like this:

# 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

If anything goes wrong with your .htaccess customization process you can move back to the default version at any time. The lines starting with # are code comments. Don’t add anything between the # BEGIN WordPress and # END WordPress comments, as the WordPress core may overwrite this part.

You need to add the custom .htaccess rules below the default rules, after # END WordPress. Before you make any changes, always back up your current .htaccess by making a copy of it and downloading it to your local machine.

1. Disable Directory Browsing

By default, directory browsing is enabled in WordPress. This means anyone on the internet can list out the contents of your folders and easily find vulnerabilities in your WordPress install. You can disable the directory browsing feature by adding the following rule to your .htaccess file:

Options -Indexes

2. Block Suspicious IP Addresses

With .htaccess, you can easily block any IP addresses you don’t want to grant access to for your site, for any reason. Simply add the IP addresses to the Deny from rules, one in each line:

Order allow,deny
Deny from xxx.xxx.xx.xx
Deny from yyy.yyy.yy.yy
Allow from all

3. Protect All Vulnerable Files

Keeping error logs and configuration files protected is an important security task because they contain vulnerable data like your database username and password. Although it’s possible to protect different configuration files such as .htaccess or wp-config.php one by one, it’s easier to use the following cumulative rule. It protects the most vulnerable files in your WordPress install from unauthorized access.

<FilesMatch "^.*(error_log|wp-config\.php|php.ini|\.[hH][tT][aApP].*)$">
Order deny,allow
Deny from all
</FilesMatch>

4. Disable Access to the wp-includes Folder

The wp-includes folder contains important WP core files. In fact, there’s no need for anyone to access these files, however they can be targeted by malicious attackers. Therefore, it’s a good security practice to disable access to this directory by adding the following rules to your .htaccess file:

<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. Set Up 301 Redirects

301 redirects are permanent redirects with which you can forward your visitors from one URL to another. They constitute the recommended, SEO-friendly way to rewrite URLs whenever you place content to a new location. You can simply manage your 301 redirects in your .htaccess file. You only need to add them below each other, one by one.

In place of /oldurl1/ and /oldurl2/, simply add the post slug. For the new URLs, always include the full URL, including the http:// or https:// protocol.

Redirect 301 /oldurl1/ https://www.yoursite.com/newurl1/
Redirect 301 /oldurl2/ https://www.yoursite.com/newurl2/

6. Restrict Direct Access to PHP Files

It’s also a good security practice to block direct access to PHP files in your theme and plugin folders inside the wp-content directory. This way you can prevent hackers from injecting malicious code into your PHP files.

RewriteCond %{REQUEST_URI} !^/wp-content/plugins/file/to/exclude\.php
RewriteCond %{REQUEST_URI} !^/wp-content/plugins/directory/to/exclude/
RewriteRule wp-content/plugins/(.*\.php)$ - [R=404,L]
RewriteCond %{REQUEST_URI} !^/wp-content/themes/file/to/exclude\.php
RewriteCond %{REQUEST_URI} !^/wp-content/themes/directory/to/exclude/
RewriteRule wp-content/themes/(.*\.php)$ - [R=404,L]

7. Remove Support for XML-RPC

The XML-RPC interface gives access to third-party apps such as Jetpack to your site so that they can post content or perform different actions on it. XML-RPC is enabled on every WordPress site by default. However, it can easily be exploited by attackers, so if you don’t want to use third-party apps on your site, it’s better to disable it. If you want you can add certain IP addresses as exceptions to the rule.

<FilesMatch "^(xmlrpc\.php)">
Order deny,allow
Allow from xxx.xxx.xx.xx
Allow from yyy.yyy.yy.yy
Deny from all
</FilesMatch>

8. Enable Browser Caching

You can speed up your site by enabling browser caching on your server so that your users’ browsers don’t have to download static files such as images and scripts all the time. The .htaccess snippet below contains the recommended browser caching expiration time frames for WordPress:

<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. Prevent Malicious Script Injections

Hackers frequently target the GLOBALS and _REQUEST variables on WordPress sites. They try to change these variables so that they can infect your site with malicious code. The following .htaccess rules make your server deny these changes:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

10. Protect Your wp-content Folder

Your wp-content folder contains your plugins, themes, image uploads, some of your backups, and other important content. Apart from static files such as images, CSS, and JavaScript, there’s no reason to give access to the wp-content directory.

You need to create a separate .htaccess file for this code snippet and place it into your wp-content folder. You can simply add all the file types you want your users’ browsers to have access to:

Order deny,allow
Deny from all
<Files ~ ".(xml|css|js|jpe?g|png|gif|pdf|docx|zip|rar)$">
Allow from all
</Files>

11. Prevent Image Hotlinking

Image hotlinking happens when another website displays your images by linking to their URL on your site. This extra traffic increases your bandwidth and may significantly slow down your site. You can easily prevent image hotlinking in your .htaccess file. The following code snippet grants access to your images only for your own URLs and Google:

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

12. Block Username Enumeration

WordPress uses a specific URL structure for author pages which display all articles belonging to the same author. Each author has an ID number starting at author=1.

For instance, if a user enters http://www.yoursite.com/?author=1 into the URL bar the browser loads the author page that displays all posts of the author together with the username. With the same technique, it’s easy to find out the username of each author. However, you can prevent username enumeration by adding the following rules to your .htaccess file:

RewriteEngine on
RewriteBase /
RewriteCond %{QUERY_STRING} author=d
RewriteRule ^ /? [L,R=301]

13. Add Custom Error Pages

Although WordPress comes with default error pages, you can also create custom error pages and serve them to your users through your .htaccess file. You need to create your error pages in HTML or PHP and upload them to your root folder (public_html on live servers). You can use the same error page for each error status code or create one for each, separately.

ErrorDocument 404 /error404.html
ErrorDocument 403 /error403.html
ErrorDocument 500 /error500.html
ErrorDocument 501 /error501.html

14. Protect Your WP Admin

If you and all your admins have a static IP you can protect your WordPress admin area by adding the following rules to your .htaccess. The code snippet below only grants access to the IP addresses you list one by one in the Allow from rules.

AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "WordPress Admin Access Control"
AuthType Basic
<LIMIT GET>
Order deny,allow
Deny from all
Allow from xxx.xxx.xx.xx
Allow from yyy.yyy.yy.yy
</LIMIT>

Next Steps

Adding custom .htaccess rules to your WordPress install makes your site more secure and your pages will also load faster than before. If you want to further increase security on your site check out our recent collection of the best security plugins for WordPress. And, if you want to know more about performance, have a look at our step-by-step tutorial that explains how you can optimize your WordPress site.

To stay updated with the latest WordPress tips and tricks, follow Developer Drive on Facebook and Twitter as well.

Home CSS Deals DesignBombs HTML HTML5 JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress