To start securing WordPress sites at the server level, the .htaccess file is one of the most powerful tools. It lets requests be filtered before they reach WordPress.
You can add the code snippets below at the very top of your .htaccess file, or just above the # BEGIN WordPress line. Important: Don't forget to back up the existing file before making changes.
1. Block Access to Sensitive Files
The first step should be to completely block outside access to the files at the heart of WordPress.
-
wp-config.php Protection: Protects your database details.
-
Error Logs and Core Files:
.htaccess: hides the file itself and the error logs.
# wp-config.php protection
<Files wp-config.php>
order allow,deny
deny from all
</Files>
# .htaccess protection
<Files .htaccess>
order allow,deny
deny from all
</Files>
2. Disable Directory Listing
It stops attackers from seeing your site's folder structure and working out which plugins you use.
# Disable directory listing
Options -Indexes
3. Restrict PHP Execution (Uploads Folder)
One of the most common attack methods is to upload a malicious PHP file to the wp-content/uploads folder and run it. If you add the code below only wp-content/uploads/ inside, to a new .htaccess file, PHP files in that folder will not run.
<Files *.php>
deny from all
</Files>
4. Disable XML-RPC Access
If you don't use a plugin such as Jetpack or a mobile app, you should disable XML-RPC to block brute force attacks that come through this protocol.
# Block XML-RPC
<Files xmlrpc.php>
order allow,deny
deny from all
</Files>
5. Block Author Scans
Attackers often try to find user names with queries such as ?author=1. To block this:
# Stop user name scanning
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} (author=\d+) [NC]
RewriteRule .* - [F]
6. Extra Security Headers
You can add these headers to take security measures at the browser level:
<IfModule mod_headers.c>
# Protection against XSS attacks
Header set X-XSS-Protection "1; mode=block"
# Clickjacking protection
Header set X-Frame-Options "SAMEORIGIN"
# Lock the MIME type
Header set X-Content-Type-Options "nosniff"
</IfModule>
Things to Watch Out For:
-
WAF Use: If you use server-side software such as ModSecurity (especially in "fast" mode), some
.htaccessrules may conflict. If you get a 500 Internal Server Error error after adding these codes, undo the last part you added and test again. -
Plugins: Plugins such as Wordfence or iThemes Security add most of these rules automatically. Make sure you don't add them twice.
