Security

WordPress .htaccess Tweaks for Security and Performance

The default WordPress htaccess rules, a safe way to edit the file, security and performance rules with notes on what each can break, and fixes for 500 errors and redirect loops.

Varun DubeyVarun Dubey
·11 min read
Code editor card showing a WordPress htaccess file with a blocked xmlrpc.php rule above the default WordPress rewrite block

The WordPress htaccess file is a plain text file that Apache reads on every request, before WordPress runs. It holds the rewrite rules that make pretty permalinks work, and it is also the place for server-level rules: block a file, compress responses, set cache headers, redirect old URLs. This guide gives you the default WordPress htaccess rules, a safe way to edit the file, a set of security and performance rules with notes on what each one can break, and the fixes for the usual failures.

Two limits first. The file only works on Apache (and servers that read it, such as LiteSpeed). On Nginx it does nothing. And the rules below are written from the Apache documentation and the WordPress developer handbook. I did not install or run them for this update, so test each one on a staging copy before it goes near a live site.

What the WordPress htaccess file does

When a visitor asks for /about/, no file called about exists on disk. The rewrite rules in .htaccess tell Apache: if the request is not a real file or folder, hand it to index.php, and let WordPress work out the page. Without those rules, every pretty permalink except the homepage returns a 404 from the web server.

Everything else in the file is optional. Custom rules sit beside the WordPress block and run for every request, which is why a bad line can take the whole site down and why you should keep the file short.

Where the .htaccess file lives

The file lives in the site root, the same folder as wp-config.php, wp-content and wp-admin. Its name starts with a dot, so it is hidden by default. In cPanel File Manager, open Settings and turn on “Show Hidden Files”. In an SFTP client, turn on hidden files in the view menu. Over SSH, use ls -la.

# From the WordPress root: show the file, its owner and its permissions
ls -la .htaccess

# Print it
cat .htaccess

If the file is missing, WordPress can create it. Go to Settings, Permalinks and click Save Changes. That only works when the web server user can write to the folder or the file. The WordPress hardening guide says all files should be writable only by your user account, “except .htaccess if you want WordPress to automatically generate rewrite rules for you”. So on a hardened site you may need to paste the rules in by hand.

Some sites also have .htaccess files in subfolders such as wp-content/uploads/. Apache reads those too, and they apply to that folder and everything under it.

The default WordPress htaccess rules

This is the default block for a single-site install, as given in the WordPress developer handbook (Advanced Administration, Apache HTTPD page):

# BEGIN WordPress
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

Line by line:

  • RewriteEngine On switches on mod_rewrite for this file.
  • The E=HTTP_AUTHORIZATION line passes the Authorization header to PHP. Some setups drop it, and REST API requests that use application passwords then fail.
  • RewriteBase / sets the URL prefix. A site in a subfolder would show that folder here.
  • RewriteRule ^index\.php$ - [L] stops processing when the request is already for index.php.
  • The two RewriteCond lines check that the request is not an existing file (-f) and not an existing directory (-d).
  • The last RewriteRule sends everything that passed those checks to index.php.

Multisite

A multisite network has its own block, inside # BEGIN WordPress Multisite and # END WordPress Multisite markers. The Network Setup screen in wp-admin shows the exact block for your network type (subdirectory or subdomain). Copy it from there rather than from a blog post, because the two versions differ. The handbook lists both for WordPress 3.5 and later.

Do not edit inside the markers

WordPress rewrites the lines between # BEGIN WordPress and # END WordPress whenever permalinks are saved or a plugin flushes rewrite rules. Anything you add inside those markers will be lost. Put your own rules above the block. The WordPress hardening guide gives the same advice: place extra code outside the BEGIN and END tags so WordPress does not overwrite it.

How to edit the htaccess file safely

Most .htaccess disasters come from skipping the same few steps. Use this order every time:

  1. Keep SSH or SFTP access ready. If a bad rule locks you out of wp-admin, you cannot undo it from the dashboard.
  2. Back up the current file. Copy it to a name Apache does not read.
  3. Change one thing at a time. Reload the homepage, a post, wp-admin and a form after each change.
  4. Read the error log if you get a 500. It names the line and the reason.
  5. Roll back at once if the site breaks. Fix it on staging, not on the live server.
# Back up before any edit
cp .htaccess .htaccess.bak-$(date +%F)

# Restore if something breaks
cp .htaccess.bak-2026-11-11 .htaccess

# On a VPS you control, check the Apache config syntax (this does not read .htaccess)
sudo apachectl configtest

Note that apachectl configtest checks the main server configuration only. Apache reads .htaccess files per request, so a syntax error there shows up as a 500 error on the next request, not at a config test. That is why the one-change-at-a-time habit matters.

Use the main server config when you can

The Apache documentation says that if you have access to the main server configuration file, you should put your configuration there instead of in .htaccess files. Directives in the main config load once at server start, not on every request. It also says that when AllowOverride permits .htaccess, httpd looks for the file in every directory, which costs performance whether or not you use it. On shared hosting you rarely have a choice. On your own VPS, move the rules into the virtual host and set AllowOverride None.

Security rules for the WordPress htaccess file

All the snippets below use Apache 2.4 syntax (Require all denied), which is what the WordPress handbook uses. Older Apache 2.2 syntax (Order deny,allow) is a different module and mixing the two is a common cause of 500 errors.

1. Protect wp-config.php

The WordPress hardening guide gives this rule and says to place it at the very top of the file:

<Files "wp-config.php">
Require all denied
</Files>

A correctly set up server never serves PHP source, so this is a second layer. The handbook also suggests moving wp-config.php one folder above the install and keeping its permissions at 400 or 440. If you are working on that file, see our guide to wp-config.php constants.

What can break: nothing for visitors. Some migration tools read the file over HTTP, which they should not do anyway.

2. Block XML-RPC if you do not use it

xmlrpc.php is the old remote publishing endpoint. It is a frequent target for password guessing. Block it only if nothing you run needs it:

<Files "xmlrpc.php">
Require all denied
</Files>

What can break: the Jetpack connection on some setups, older mobile apps, and any tool that posts through XML-RPC. Check the access log for requests to xmlrpc.php before you block it.

3. Turn off directory listing

Options -Indexes

Without an index file, Apache can list a folder’s contents. This line stops that. The Apache handbook page used by WordPress lists Options values such as FollowSymLinks, which mod_rewrite needs, so do not replace the whole Options line with Options None. Use -Indexes and leave the rest alone.

What can break: on some hosts, Options is locked by AllowOverride, and this line gives a 500 error. The error log will say the directive is not allowed here.

4. Block PHP execution in uploads

Uploads should hold images and documents, not code. If a vulnerable plugin lets someone upload a PHP file, this rule stops it from running. Create a separate file at wp-content/uploads/.htaccess with only this content:

<FilesMatch "(?i)\.(php|phtml|phar)$">
Require all denied
</FilesMatch>

Patching a plugin does not remove files an attacker already uploaded, so this rule is a safety net and not a cleanup. After any upload flaw, also list the uploads folder for PHP files:

find wp-content/uploads -type f -iname "*.php*"

What can break: a few plugins store PHP files in uploads on purpose (some cache and form plugins do). If a plugin stops working after this change, check whether it writes PHP there before you remove the rule.

5. Protect the .htaccess file itself

Most Apache installs already deny web access to files that start with .ht. If you want it spelled out:

<Files ".htaccess">
Require all denied
</Files>

6. Limit wp-admin by IP address

If you work from a fixed IP address, you can put this in wp-admin/.htaccess. The address below is a documentation example; replace it.

Require ip 203.0.113.10

<Files "admin-ajax.php">
Require all granted
</Files>
<Files "admin-post.php">
Require all granted
</Files>

What can break: this is the rule that breaks the most. Front-end features use admin-ajax.php and admin-post.php for logged-out visitors, which is why they are allowed above. Even so, it locks out every teammate and yourself when your IP changes. Skip it unless the site has one admin on a static address.

7. Block author enumeration

Visiting /?author=1 redirects to the first user’s author page and reveals the username. This rule sends those requests to the homepage and leaves wp-admin alone:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/wp-admin
RewriteCond %{QUERY_STRING} (^|&)author=\d
RewriteRule ^ /? [L,R=301]
</IfModule>

What can break: without the wp-admin condition, the Posts screen filter by author (edit.php?author=2) stops working. Author archive URLs in the form /author/name/ still show the username in the path, so this is a small gain on its own. Changing the display name and nicename on users matters more.

8. Stop image hotlinking

Replace example.com with your domain:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
RewriteCond %{HTTP_REFERER} !google\. [NC]
RewriteCond %{HTTP_REFERER} !bing\. [NC]
RewriteRule \.(jpe?g|png|gif|webp)$ - [F,NC,L]
</IfModule>

What can break: feed readers, email clients that proxy images, social sharing previews and some CDNs send a different referrer or none. Test an Open Graph preview after adding it.

Performance rules for the WordPress htaccess file

These rules rely on Apache modules. If a module is missing, the lines inside an IfModule wrapper are skipped quietly, which is safer than a 500 error but also means you need to check that the headers really arrive.

9. Compress text responses

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml
AddOutputFilterByType DEFLATE application/javascript application/json application/xml image/svg+xml
</IfModule>

Images in JPEG, PNG and WebP are already compressed, so they are left out. Many hosts and CDNs compress at a higher layer already. Check before you add it, or you may compress twice.

10. Browser caching with Expires headers

<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType text/html "access plus 0 seconds"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>

A one-year lifetime is safe for files whose URL changes when the file changes. WordPress adds a version query string to most plugin and theme assets (for example ?ver=6.9). Files that keep the same URL after an edit, such as a logo you replace by name, will look stale for returning visitors until the cache expires.

11. Cache-Control for static files

<IfModule mod_headers.c>
<FilesMatch "\.(css|js|woff2|jpe?g|png|webp|svg)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
</IfModule>

The immutable value tells browsers not to revalidate the file during its lifetime. Use it only for versioned files. If you are not sure that every asset URL changes when the content changes, drop immutable and keep max-age.

12. Verify the headers arrive

Check from the command line, not by guessing:

curl -sI https://example.com/wp-content/themes/your-theme/style.css | grep -i -E "cache-control|expires|content-encoding"

# Ask for compressed content
curl -sI -H "Accept-Encoding: gzip" https://example.com/ | grep -i content-encoding

If a caching plugin or CDN is in front, it may set its own headers and override yours. See our shorter guide on gzip, browser caching and security rules for a second view of the same rules.

Redirect rules

13. Force HTTPS

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
</IfModule>

Behind a load balancer or Cloudflare, Apache may see every request as plain HTTP, and this rule then loops forever. In that case test the forwarded protocol header instead:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]

If your host or CDN already redirects to HTTPS, skip this rule. Two layers redirecting is the usual cause of “too many redirects”.

14. One canonical hostname

Pick www or non-www and redirect the other. Make sure the WordPress Address and Site Address settings agree with your choice, or WordPress will redirect back and cause a loop.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
</IfModule>

15. Redirect a few old URLs

Redirect 301 /old-page/ https://example.com/new-page/

A few lines are fine. For hundreds of redirects, use a redirect plugin or the main server config, because every line in .htaccess is read on every request.

Where to place the rules

Put your own rules above the WordPress block. Order matters for redirects: the HTTPS and hostname redirects go first, then security rules, then headers, then the WordPress block last. This layout shows the idea:

# 1. Redirects (HTTPS, canonical host)
# 2. Security rules (wp-config.php, xmlrpc.php, Options -Indexes)
# 3. Performance rules (deflate, expires, cache-control)

# BEGIN WordPress
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

What breaks and how to fix it

500 Internal Server Error after an edit

A directive Apache does not know, or is not allowed to use here, returns a 500. The Apache documentation says to check the httpd error log, which names the directive. For example, a line such as .htaccess: DirectoryIndex not allowed here means AllowOverride does not permit that directive. Restore the backup, then add rules back one at a time.

# On a VPS: the error log location varies by distro
sudo tail -n 20 /var/log/apache2/error.log    # Debian and Ubuntu
sudo tail -n 20 /var/log/httpd/error_log      # RHEL family

On shared hosting the error log is in cPanel under Errors, or in the logs folder of your account. If WordPress still loads but behaves oddly, turn on WP_DEBUG and the debug log, though a pure Apache error will not appear there because WordPress never ran.

Pretty permalinks return 404

The WordPress block is missing or the file was not read. Re-save permalinks. If that does nothing, check that mod_rewrite is on and that AllowOverride allows rewrite rules. The Apache documentation says the default for AllowOverride is None, in which case .htaccess files are ignored completely. On a VPS, the virtual host needs AllowOverride All (or at least FileInfo) for the web root.

Rules have no effect

Three causes cover most cases. The server is Nginx, AllowOverride is None, or a caching layer in front is serving old responses. Purge the cache, then test with curl -sI from a clean session.

Redirect loop

Usually two layers are redirecting: a plugin, the host, Cloudflare and .htaccess. Turn off all but one. For HTTPS behind a proxy, use the forwarded-protocol version shown earlier.

wp-admin or REST API stops working

Look for IP restrictions on wp-admin, a block on wp-json or a hotlink rule that catches script files. The Authorization header line in the WordPress block also matters for REST requests with application passwords, so do not delete it.

Apache, LiteSpeed and Nginx

LiteSpeed reads Apache .htaccess rules and can use most of them. Nginx does not read .htaccess at all, so every snippet above has an Nginx equivalent in the server config instead:

Apache (.htaccess)

Nginx equivalent

Options -Indexes

autoindex off;

mod_deflate

gzip on; and gzip_types

mod_expires

expires directive in a location block

Deny xmlrpc.php

location = /xmlrpc.php { deny all; }

Rewrite to index.php

try_files $uri $uri/ /index.php?$args;

Managed hosts on Nginx usually handle security and caching in their own layer. Ask the host before you replace those settings.

Quick checklist

  1. Back up .htaccess and keep SSH or SFTP open.
  2. Leave the WordPress block alone and add your rules above it.
  3. Add one rule, then test the homepage, a post, wp-admin and a form.
  4. Check headers with curl -sI instead of trusting the file.
  5. If you own the server, move the rules into the virtual host.
  6. If you get a 500, read the error log first.

Frequently asked questions

Where is the WordPress htaccess file?

In the site root, beside wp-config.php. It is hidden by default, so turn on hidden files in your file manager or use ls -la over SSH.

What is the default WordPress htaccess code?

The block between # BEGIN WordPress and # END WordPress shown earlier in this guide. It sends requests for pages that are not real files to index.php.

How do I regenerate a lost or broken htaccess file?

Rename the broken file, then go to Settings, Permalinks and click Save Changes. WordPress writes a fresh default block if it has permission. If it does not, paste the default block in by hand.

Can I edit .htaccess from the WordPress dashboard?

Not by default. Some plugins edit it for you. Editing over SFTP or SSH is safer, because you can undo a mistake even when wp-admin is down.

Does .htaccess work on Nginx?

No. Nginx ignores it. Put the same rules in the Nginx server block.

Why does my htaccess change do nothing?

Either the server does not read the file (Nginx or AllowOverride None), the module is not enabled, or a cache is serving old responses.

Is it safe to block xmlrpc.php?

Yes, if nothing you use depends on it. Jetpack on some setups and older mobile apps do. Look at your access log first.

Sources

What I did not confirm: I did not run any of these rules on a live server for this update. The module names and directive syntax come from the Apache documentation, and the specific rules for author enumeration, hotlinking and uploads are common patterns that I checked for syntax only. The XML-RPC compatibility notes for Jetpack and mobile apps are general behaviour I did not retest against current versions.

Part of the Wbcom Designs family

The all-in-one WordPress community stack

Also ours: wbcomdesigns.comvapvarun.combrndle.com