Free resource

WordPress .htaccess Security Template (Apache 2.4, With What It Breaks)

By , Lead SEO & Co-founder 9 min read
A server room entrance at night with a heavy steel door frame fitted with layered glowing filter gates in cyan, one gate glowing crimson as it blocks a stream, racks visible behind and a control panel mounted on the wall

This WordPress htaccess security template is the one I'd paste into a small business site today: Apache 2.4 syntax only, and every block tells you what it can break before you hit save. Most templates floating around were written for Apache 2.2 and still carry headers that browsers stopped reading years ago. This one is shorter, and every line has a job.

Below you get the full template, split into blocks you can add one at a time, a one-line test for each block, and a list of the popular rules I left out on purpose (with the reason). Nothing to download, nothing to sign up for. Copy what you need.

If you'd rather not touch the server at all, that's fine too. You can ask me to set it up as part of a care plan, and I'll reply with a plan and a fixed quote within one business day.

What this WordPress htaccess security template does (and doesn't)

The .htaccess file (a small settings file that Apache web servers read on every request) sits in the main folder of your WordPress site. WordPress already uses it for pretty permalinks. You can add rules above that WordPress section to block files, stop directory listings and send security headers.

Here's what the template covers:

  • Stops visitors from browsing your folders like a file cabinet
  • Blocks web access to wp-config.php and to the backup and log files people forget about
  • Stops PHP from running in places it never should (wp-includes and the uploads folder)
  • Blocks the cheapest username-guessing trick (?author=1)
  • Sends four modern security headers and removes one that leaks your PHP version
  • Offers optional, commented-out rules for XML-RPC and for locking the login page to your IP

What it doesn't do: clean a hacked site, replace updates, or protect a site on Nginx. Nginx ignores .htaccess completely. If your host runs Nginx (many managed WordPress hosts do), these rules belong in the server configuration, and your host has to add them.

LiteSpeed servers, which a lot of cPanel hosts use, read .htaccess the same way Apache does, so the template works there too.

Who this template is for

It's for you if your site runs on cPanel, Plesk, a VPS with Apache, or LiteSpeed shared hosting, and you (or your web person) can open files through the hosting File Manager or SFTP (a secure way to copy files to and from the server).

It's not for you if:

  • You're on WordPress.com, Wix, Squarespace or Shopify. There's no .htaccess to edit.
  • Your host runs Nginx only. Send this page to their support and ask what they already block.
  • The site is hacked right now. Hardening a hacked site is locking the door with the burglar still inside. Clean it first.

How to add the rules without taking the site down

A single typo in .htaccess gives every visitor a 500 error (the server's generic "something broke" page). So go slowly:

  1. Make a backup copy. In cPanel's File Manager, turn on "Show Hidden Files" in Settings first, because files starting with a dot are hidden by default. Download .htaccess to your computer before changing anything.
  2. Paste above # BEGIN WordPress. WordPress rewrites the lines between its own # BEGIN WordPress and # END WordPress markers when you save permalinks. Anything you put inside that section can vanish.
  3. Add one block at a time. Save, reload the site in a private window, click around, then move to the next block.
  4. Run the test line for that block. Each block below comes with a curl command (a tool that fetches a web address from the command line; it ships with Windows 10 and 11, macOS and Linux).
  5. If anything breaks, delete the last block. You'll know exactly which one did it.

If you do hit a 500 error, my guide to the usual causes of an .htaccess 500 error walks through the fix in a few minutes.

The template, block by block

Replace example.com in the test commands with your own domain. Every rule uses the Apache 2.4 Require syntax. The old Order allow,deny lines still work on many hosts, but only because a compatibility module is loaded, and Apache's own upgrade notes warn that mixing old and new syntax can give results you didn't expect.

Block 1: Turn off directory listings and the server signature

If a folder has no index.php, Apache may show a clickable list of every file in it. That's how strangers find your plugin versions and old backups. This is the most useful single line in the whole file.

.htaccess / Apache
# Block 1: no folder listings, no Apache version on error pages.
# Could break: almost nothing. If the site shows a 500 error after this, your host
# doesn't allow "Options" in .htaccess. Remove the Options line and ask them to set it.
Options -Indexes
ServerSignature Off

Test: curl -s -o /dev/null -w "%{http_code}\n" https://example.com/wp-includes/ should print 403, not 200.

Block 2: Protect wp-config.php and leftover files

Your wp-config.php holds the database password. PHP normally runs it rather than showing it, but a server misconfiguration or a bad PHP update can turn that into a plain-text download. The WordPress hardening guide recommends this exact Require all denied block.

The second part catches the files people leave behind: wp-config.php.bak, backup.sql, debug.log, and the error_log files that cPanel writes when PHP complains.

.htaccess / Apache
# Block 2: deny web access to the config file and to backup, log and dump files.
# Could break: a plugin that serves its own .log or .sql file to visitors (rare).
# PHP and WordPress can still read these files. Only browsers are refused.
<Files "wp-config.php">
    Require all denied
</Files>

<FilesMatch "(?i)(?:\.(?:bak|old|orig|save|swp|sql|log|dist)|~)$">
    Require all denied
</FilesMatch>

<FilesMatch "^(?:readme\.html|license\.txt|wp-config-sample\.php|\.user\.ini|php\.ini|error_log)$">
    Require all denied
</FilesMatch>

Test: curl -s -o /dev/null -w "%{http_code}\n" https://example.com/wp-config.php should print 403.

You don't need a rule for .htaccess itself. Apache's stock configuration already refuses any file starting with .ht, so the "protect this htaccess file" block in older templates does nothing on most servers.

Block 3: Stop PHP from running inside wp-includes

The wp-includes folder is WordPress's own library. Nothing in it should ever be opened directly by a browser. These rules come from the official hardening guide, lightly commented.

.htaccess / Apache
# Block 3: refuse direct requests to PHP files inside wp-includes and wp-admin/includes.
# Could break: WordPress multisite that still uses ms-files.php for uploads. Skip it there.
<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>

Test: curl -s -o /dev/null -w "%{http_code}\n" https://example.com/wp-includes/version.php should print 403.

Block 4: Block username scans

Visit yoursite.com/?author=1 on a typical WordPress site and it redirects to /author/your-login-name/. Bots use that to collect real usernames before they start guessing passwords. This block refuses the request instead.

.htaccess / Apache
# Block 4: refuse "?author=N" lookups outside the dashboard.
# Could break: author archive links if your permalinks are set to "Plain".
# With pretty permalinks (/author/name/), archives keep working.
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/wp-admin/ [NC]
    RewriteCond %{QUERY_STRING} (?:^|&)author=\d [NC]
    RewriteRule ^ - [F,L]
</IfModule>

Test: curl -s -o /dev/null -w "%{http_code}\n" "https://example.com/?author=1" should print 403.

Usernames also leak through the REST API at /wp-json/wp/v2/users. That one is better handled inside WordPress, because some plugins need the API. Wordfence and most security plugins have a switch for it.

Block 5: Refuse TRACE and TRACK requests

These are debugging methods (types of request) no WordPress site needs. They're low risk, but blocking them costs nothing and keeps scanner reports quiet.

.htaccess / Apache
# Block 5: refuse TRACE, TRACK and DEBUG request methods.
# Could break: nothing a normal website uses. On a VPS, "TraceEnable Off" in the
# main Apache config is the cleaner way to do the same thing.
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} ^(?:TRACE|TRACK|DEBUG)$ [NC]
    RewriteRule ^ - [F,L]
</IfModule>

Block 6: Modern security headers

Security headers are short instructions your server sends with every page, telling the browser what it may and may not do with it. This block sends the four that still matter and removes the X-Powered-By header, which advertises your exact PHP version.

Note the word always. Apache's mod_headers documentation explains that headers set without it can be missing from error pages and redirects, and that append (which most old templates use) can send a header twice.

.htaccess / Apache
# Block 6: security headers for every response, including errors and redirects.
# Could break: X-Frame-Options stops other websites from showing your pages in a frame
# (a partner site embedding your booking page, for example). Permissions-Policy turns off
# camera, microphone and location access, so drop "geolocation=()" if you run a store
# locator that asks for the visitor's location.
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
    Header always unset X-Powered-By
    Header unset X-Powered-By

    # HSTS starts at 5 minutes. Raise it once HTTPS works on every page (see below).
    Header always set Strict-Transport-Security "max-age=300"

    # Content Security Policy: leave this commented out until you've read the CSP guide.
    # Header always set Content-Security-Policy-Report-Only "default-src 'self'; ..."
</IfModule>

Test: curl -sI https://example.com/ | grep -iE "x-frame|x-content|referrer|permissions|strict" should list all five headers.

HSTS (Strict-Transport-Security, a header that tells browsers to use HTTPS only for your domain) is the one header that can lock visitors out if you rush it. Browsers remember it for the full max-age. Start at 300, raise it to 86400 (one day) after a week with no problems, then to 31536000 (one year). Add includeSubDomains only when every subdomain, including old ones like mail. or shop., works over HTTPS. MDN's HSTS reference covers the details.

The reasoning behind each header, and the three old ones to delete, is in my post on which WordPress security headers to keep. The Content Security Policy line needs its own process, which is in the CSP rollout guide.

Block 7 (optional): Turn off XML-RPC

xmlrpc.php is an old remote-publishing door that bots love for password guessing. Blocking it is a good idea for many sites and a bad one for others.

.htaccess / Apache
# Block 7 (optional): refuse all requests to xmlrpc.php.
# Could break: Jetpack, some mobile and desktop publishing apps, and services that
# post to your site remotely. Read the XML-RPC guide before you uncomment this.
# <Files "xmlrpc.php">
#     Require all denied
# </Files>

Before uncommenting, check my guide on whether to disable xmlrpc.php. It lists the setups that need it.

Block 8 (optional): Lock the login page to your IP

This is for a site with one or two admins on fixed IP addresses. Everyone else gets a 403 at the login page.

.htaccess / Apache
# Block 8 (optional): only these IP addresses can open wp-login.php.
# Could break: logins for anyone not on the list, including you on hotel Wi-Fi.
# Behind Cloudflare or another proxy, Apache sees the proxy's IP, not yours,
# so this rule locks everyone out unless mod_remoteip is configured.
# <Files "wp-login.php">
#     Require ip 203.0.113.10
#     Require ip 198.51.100.0/24
# </Files>

Replace the sample addresses with yours. Two Require ip lines mean "either one is fine".

Block 9: A separate file for the uploads folder

This one does not go in the main .htaccess. Create a new file called .htaccess inside wp-content/uploads/. Uploads should hold images and PDFs, so any PHP file there is either a mistake or malware.

.htaccess / Apache
# Block 9: save as wp-content/uploads/.htaccess
# Stops PHP files in uploads from running. Could break: a rare plugin that keeps
# executable PHP in uploads. If one breaks, ask its developer why.
<FilesMatch "(?i)\.(?:php[0-9]?|phtml|phar|pht)$">
    Require all denied
</FilesMatch>

Test: you don't need a real PHP file for this. Check that curl -s -o /dev/null -w "%{http_code}\n" https://example.com/wp-content/uploads/test.php prints 403 or 404, not a blank 200.

The htaccess security rules I left out (and why)

Older templates carry rules that now do nothing or do harm. Here's what I removed:

Old rule Why it's gone
X-XSS-Protection "1; mode=block" Modern browsers ignore it, and OWASP's header guidance says not to set it or to send 0
Feature-Policy Replaced by Permissions-Policy, which uses a different syntax
Referrer-Policy "no-referrer-when-downgrade" Leaks full page URLs, including search terms and tracking parameters, to other sites
order allow,deny / deny from all Apache 2.2 syntax. Works only through a compatibility module
Header always append X-Frame-Options append adds a second value when your host already sends the header, and conflicting values are left for each browser to sort out
php_value upload_max_filesize 64M Works only with the old mod_php setup. On PHP-FPM, which most hosts now run, it causes a 500 error
Block POST requests over HTTP/1.0 Catches almost nothing today, and the occasional monitoring tool still uses HTTP/1.0
BrowserMatch MSIE and Vary User-Agent lines Written for Internet Explorer 6. The Vary line also hurts caching

For upload limits, put the PHP settings in a .user.ini file in the site's main folder instead. PHP's manual confirms that .user.ini files are read by CGI/FastCGI setups, including PHP-FPM, and re-read every five minutes by default:

Config
; .user.ini in the WordPress root. Raises upload limits on PHP-FPM hosts.
; Could break: nothing, but your host may cap these values lower. Changes can take 5 minutes.
upload_max_filesize = 64M
post_max_size = 128M
expose_php = Off

When to call someone instead

Do it yourself if you're comfortable with File Manager, you have a backup, and the site is healthy. The whole template takes about 20 minutes with testing.

Hand it off if:

  • The site is on a VPS and nobody is sure whether Apache, Nginx or both are serving it
  • There's a CDN or proxy in front (Cloudflare, Sucuri) and you want the IP lock or HSTS
  • The site was hacked recently, so rules may already be in .htaccess that you didn't write
  • You run WooCommerce or a booking plugin and can't afford a broken checkout while you test

Not sure what your site is exposing right now? The free check I run on small business sites includes a look for open directory listings and exposed files, with a report within two business days.

WordPress htaccess security FAQ

Where do I put security rules in the WordPress .htaccess file?

Above the # BEGIN WordPress line. WordPress manages everything between its own markers and can overwrite that section when you save permalinks or when a plugin changes rewrite rules. Rules above the markers are left alone. The one exception is the uploads rule, which goes in a separate .htaccess file inside wp-content/uploads/.

Does .htaccess security work on Nginx?

No. Nginx doesn't read .htaccess files at all, so the rules are silently ignored. On Nginx, the same protections are written as location blocks in the server configuration. On managed WordPress hosting, ask support which of these protections they already apply. Many block wp-config.php and directory listings by default, and most can add the rest for you.

Will these rules slow down my site?

Not in any way you could measure. Apache reads .htaccess on every request anyway because WordPress already uses it for permalinks. A dozen extra lines of simple matching add microseconds. The header block adds a few hundred bytes per response, which is smaller than one favicon. Page caching and image sizes matter thousands of times more.

Is this enough to stop my WordPress site from getting hacked?

No, and anyone who says one file is enough is selling something. Most WordPress hacks come through outdated plugins and stolen passwords. These rules limit the damage and close easy doors. Updates, two-factor login, backups and a security plugin do the heavy lifting. The template is one layer of several.

Final thoughts

Treat .htaccess like a seatbelt, not a force field. Add the blocks one at a time, run each test, and keep the backup copy until you've clicked through the whole site, including the checkout and contact forms.

If you'd like someone to apply this, watch the updates and keep an eye on the site every month, that's what my WordPress maintenance plan is for, starting at $250 a month. Or send me a few details through the questionnaire and I'll tell you what I'd change on your site first.

Want a second pair of eyes on your site?

Tell me what's going on in the wordpress maintenance questionnaire. I reply with a plan and a fixed quote within one business day.

Starting at $250/mo Start the questionnaire