WordPress Logo – Athemeart WordPress Themes

WordPress htaccess Guide: Essential Rules Every Site Owner Should Know

The WordPress htaccess file is a tiny text file with an outsized job. It sits in your site’s root folder, it has no name before the dot, and it quietly decides how Apache handles every request: which URL loads which page, which files visitors may open, where old links redirect, and how long browsers cache your images. When it is right, you never think about it. When it is wrong, you see a white screen with a 500 error.

This guide is a practical manual for the htaccess file in WordPress. You will learn what the file does, where to find it, how to edit it safely over cPanel, SFTP or SSH, what the WordPress default htaccess block really contains, and which WordPress .htaccess rules are worth adding for security, redirects and speed. Every snippet uses modern Apache 2.4 syntax with a fallback where older servers still need it, because that is where many copy-pasted tutorials quietly break. The advice applies to current WordPress releases, including the 7.0 branch that .

Quick answer: the WordPress .htaccess file is an Apache configuration file in your site’s root directory. WordPress writes a short block of rewrite rules into it so pretty permalinks work. You can add your own rules above or below that block for redirects, security and caching, but never inside it, and always keep a backup copy first.

1. What Is the WordPress .htaccess File?

.htaccess stands for “hypertext access.” It is a per-directory configuration file for the Apache web server, and LiteSpeed reads it too. Instead of editing the server’s main configuration, which you usually cannot touch on shared hosting, you drop a .htaccess file into a folder and Apache applies those directives to that folder and everything beneath it.

Understanding how .htaccess works

On each request, Apache walks from the web root down to the requested folder and reads every .htaccess file it finds on the way. Two things follow from that. First, the rules apply instantly, with no server restart, which is why the file is so convenient. Second, Apache re-reads the file on every request, which is why the Apache project itself . For most WordPress owners on shared or managed Apache hosting, the convenience wins.

A directive only works if the host allows it. The server’s AllowOverride setting controls which directive groups (rewrite, headers, authorization, options) a .htaccess file may use, and the matching Apache module (mod_rewrite, mod_headers, mod_expires, mod_deflate) must be loaded. When a directive is not allowed or not available, the result is usually a 500 error.

How a request flows through .htaccess in WordPressA browser request reaches Apache, which reads .htaccess. If the file or folder exists it is served directly, otherwise the request goes to index.php and WordPress builds the page.VisitorGET /sample-post/Apache / LiteSpeedreads .htaccess filesfrom root downwardmod_rewriteIs there a real fileor folder at that URL?YESNOServe the fileimage, CSS, JS, PDF/index.phpWordPress builds the page
Figure 1: The WordPress rewrite block in .htaccess sends every “virtual” URL to index.php, while real files are served as they are.

Where is the .htaccess file located in WordPress?

The main file lives in the same folder as wp-config.php, wp-admin and wp-content. That folder is called the web root, and its name depends on the host:

Hosting setup Typical web root
cPanel shared hosting public_html (add-on domains often use public_html/yourdomain.com)
Plesk httpdocs
VPS or cloud server (Apache) /var/www/html or /var/www/yourdomain.com/public_html
Local environments The htdocs or site folder inside XAMPP, MAMP or Local

You can also place extra .htaccess files in subfolders. They affect only that folder and its children, which makes them ideal for tightly scoped rules such as blocking PHP execution inside wp-content/uploads.

Where .htaccess files live in a WordPress installationA folder tree of a WordPress site showing the main .htaccess in the web root plus optional .htaccess files in wp-admin and wp-content/uploads.WORDPRESS FOLDER STRUCTUREpublic_html/├─ .htaccessMAIN FILE: permalinks, redirects, headers, caching├─ index.php├─ wp-config.php├─ wp-admin/│ └─ .htaccessOPTIONAL: IP or password rules for the dashboard├─ wp-content/│ ├─ plugins/│ └─ uploads/│ └─ .htaccessOPTIONAL: block PHP execution in uploads└─ wp-includes/
Figure 2: One main .htaccess in the web root, plus optional per-folder files for tightly scoped rules.

Why WordPress uses .htaccess

WordPress builds pages dynamically, so a URL like /wordpress-htaccess/ does not match a real file on disk. Without help, Apache would return a 404. The rewrite rules in .htaccess tell Apache: “if there is no real file or folder here, hand the request to index.php.” That is the entire trick behind pretty permalinks.

Here is the WordPress default htaccess block that current installs generate on a single-site Apache setup, matching what the lists as the basic configuration:

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
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]
</IfModule>
# END WordPress
Line What it does
<IfModule mod_rewrite.c> Runs the block only if the rewrite module is loaded, so a missing module does not crash the site.
RewriteEngine On Switches on the rewrite engine for this directory.
RewriteRule .* - [E=HTTP_AUTHORIZATION:…] Passes the Authorization header to PHP so REST API and application-password logins keep working on CGI or FastCGI setups.
RewriteBase / Sets the base path to the site root (WordPress writes the subfolder here for subdirectory installs).
RewriteRule ^index\.php$ - [L] Requests for index.php itself are left alone and processing stops.
RewriteCond … !-f and !-d Apply the next rule only when the URL is not a real file and not a real directory.
RewriteRule . /index.php [L] Sends everything else to WordPress, the last rule ([L]) in the chain.

Older tutorials, including some of the most-linked ones, show a shorter version without the Authorization line or the IfModule wrapper. That older block still routes permalinks, but if you restore from it you can lose the header pass-through. Prefer the block above, or simply let WordPress regenerate it (see section 3).

Multisite networks use a different block. If you enabled Multisite, WordPress writes a # BEGIN WordPress Multisite section instead. For a subdirectory network it looks like this:

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

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
# END WordPress Multisite

A subdomain network drops the optional ([_0-9a-zA-Z-]+/)? prefixes. Always copy the exact block WordPress shows under Network Admin → Settings → Network Setup rather than typing it by hand.

Difference between .htaccess and wp-config.php

Both files sit in the root folder, and beginners mix them up constantly. The easiest way to remember it: .htaccess talks to the web server, while wp-config.php talks to WordPress.

.htaccess wp-config.php
Read by Apache or LiteSpeed, before PHP starts PHP, when WordPress boots
Language Apache directives PHP constants and variables
Typical contents Rewrites, redirects, access rules, headers, caching Database credentials, salts, table prefix, debug flags, memory limit
A syntax error causes 500 error on the whole site White screen or “critical error” message
Works on Nginx No Yes

2. How to Access and Edit the WordPress .htaccess File

You cannot edit this file from the WordPress dashboard unless a plugin adds an editor, and a plugin editor is the last thing you want when a bad rule has already taken the dashboard offline. Learn at least one file-based method. Whichever you pick, download a copy of the current file first.

Access .htaccess through cPanel File Manager

  1. Log in to cPanel and open File Manager under the Files section.
  2. Click Settings in the top-right corner, tick Show Hidden Files (dotfiles), and save.
  3. Open public_html (or your site’s document root).
  4. Right-click .htaccess, choose Download to keep a backup, then choose Edit (or Code Editor).
  5. Make one change, click Save Changes, and immediately reload your site in a private window.
cPanel File Manager with hidden files enabled (illustrative mockup)A simplified screenshot-style illustration of cPanel File Manager. The Settings dialog shows Show Hidden Files checked and the .htaccess file is highlighted in the public_html folder.https://yourdomain.com:2083/…/filemanager/index.htmlFile Manager+ File+ FolderUploadDownloadEditSettings▾ /home/username▸ etc▸ logs▾ public_html▸ wp-admin▸ wp-content▸ wp-includesNameSizePermissionswp-admin4 KB0755wp-content4 KB0755.htaccess1.02 KB0644index.php405 B0644wp-config.php3.1 KB0600PreferencesShow Hidden Files (dotfiles)SaveIllustrative mockup. Your host’s theme and layout may differ.
Figure 3: Enable “Show Hidden Files (dotfiles)” in cPanel File Manager, or .htaccess will not appear in the list.

How to show hidden files in File Manager

Files that start with a dot are hidden by default almost everywhere. If you cannot see .htaccess, the file is probably there already:

  • cPanel: File Manager → Settings → Show Hidden Files (dotfiles).
  • FileZilla: Server menu → Force showing hidden files, then reconnect or refresh.
  • Plesk and DirectAdmin: turn on the “show hidden files” option in the file manager toolbar or settings.
  • SSH: use ls -la, because plain ls hides dotfiles.

Edit .htaccess using FTP or SFTP

Use SFTP when your host offers it, because plain FTP sends your password unencrypted. Connect with FileZilla, Cyberduck or WinSCP, open the web root, drag .htaccess to your computer, and keep that downloaded file untouched as your backup. Edit a second copy in a plain-text editor such as VS Code, Notepad++ or Sublime Text, never in a word processor, which can add smart quotes and hidden formatting. Save with UTF-8 encoding and Unix (LF) line endings, then upload it back and test.

Edit .htaccess through SSH

SSH is the fastest route if you have it, and it lets you check logs while you work:

cd ~/public_html                      # or /var/www/html
ls -la | grep htaccess                # confirm the file exists
cp .htaccess .htaccess.bak-$(date +%F)  # dated backup
nano .htaccess                        # edit, then Ctrl+O to save, Ctrl+X to exit
chmod 644 .htaccess                   # correct permissions
curl -I https://example.com/          # check the response headers

Whichever method you use, test two URLs after every change: the homepage and one inner page, such as a blog post. A site that loads the homepage but returns 404 on inner pages points to a broken rewrite block.

3. How to Create and Restore a WordPress .htaccess File

You will meet this situation sooner or later: the file is missing after a migration, a plugin wiped it, or a bad edit left it corrupted. The good news is that WordPress can rebuild its own block in seconds.

Create a new .htaccess file

Some file managers refuse to create a file whose name starts with a dot. If yours does, create htaccess.txt on your computer, upload it to the web root, then rename it to .htaccess on the server. In cPanel, simply click + File and type .htaccess. Over SSH, run touch .htaccess && chmod 644 .htaccess.

Generate default WordPress .htaccess rules

You have three reliable ways to regenerate the WordPress default htaccess block, and none of them requires you to remember the code.

  1. Dashboard: go to Settings → Permalinks and click Save Changes without changing anything. WordPress rewrites its block if the file is writable.
  2. WP-CLI: run the command below from the site root. The --hard flag forces WordPress to write the .htaccess file.
  3. Manual paste: copy the block from section 1 into the file between your own rules.
wp rewrite structure '/%postname%/' --hard
wp rewrite flush --hard

If WordPress cannot write to the file, it shows the rules on the Permalinks screen with a notice that the file is not writable. Copy them into the file by hand, or temporarily set the file to 644 with the correct owner and save permalinks again.

Restore the original .htaccess file

  1. Rename the current file to .htaccess.broken (do not delete it yet, you may want to compare it later).
  2. Upload your downloaded backup as .htaccess, or create a fresh file.
  3. If you had no backup, paste the default block from section 1 and save.
  4. Visit Settings → Permalinks and click Save Changes to refresh WordPress’s own rules.

Fix missing or corrupted .htaccess files

Symptom Likely cause Fix
Homepage works, every other page is a 404 File missing or rewrite block removed Regenerate with Save Changes or wp rewrite flush --hard
500 error right after an edit Syntax error or disallowed directive Rename the file, then re-add rules one at a time
File keeps vanishing Migration or deployment script overwrites it Exclude .htaccess from the sync, or store the rules in the server config
WordPress will not write to the file Wrong owner or permissions Set 644 and fix ownership; confirm with your host
Duplicate blocks from several plugins Caching or security plugins each added their own Clean up the duplicates and keep one set of marker-wrapped blocks

4. Essential WordPress .htaccess Rules Every Site Owner Should Know

This section covers the handful of rules that deliver the most value for the least risk. Add them one at a time, outside the # BEGIN WordPress and # END WordPress markers. Where a rule is about access control, the snippets use Apache 2.4 syntax (Require) with an IfModule fallback for older 2.2 servers, because the legacy Order allow,deny style that fills many tutorials triggers a 500 error on servers without mod_access_compat.

Default WordPress permalink rules

Nothing to paste here: WordPress maintains these for you (see the block in section 1). Your job is to leave them alone, keep Settings → Permalinks on a structure such as “Post name,” and put your own directives above or below the markers. If you ever see 404 errors on inner pages, this is the first place to look.

Force HTTPS redirection

After you install an SSL certificate and update your site address to https, send every http request to the secure version with a permanent redirect:

# Force HTTPS (works behind Cloudflare and other proxies)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

The extra X-Forwarded-Proto condition prevents the classic “too many redirects” loop on sites that sit behind a CDN or reverse proxy, where Apache itself only ever sees plain http traffic.

Redirect www to non-www (and vice versa)

Search engines treat www.example.com and example.com as separate hosts, so pick one and redirect the other. To remove the www:

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

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

Redirect old URLs to new URLs (301 redirects)

A 301 tells browsers and search engines that a page has moved permanently and passes ranking signals to the new address. For a few URLs the Redirect directive is enough; for patterns, use RedirectMatch. Place these above the WordPress block so they run before the catch-all rewrite.

Redirect 301 /old-page/ https://example.com/new-page/
RedirectMatch 301 ^/category/news/(.*)$ https://example.com/blog/$1

Block access to sensitive WordPress files

Some files should never be served over the web. This block denies direct requests to configuration, credential, log and readme files:

<FilesMatch "^(wp-config\.php|\.htpasswd|php\.ini|debug\.log|readme\.html|license\.txt)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
</FilesMatch>

Hiding readme.html and license.txt stops casual version fingerprinting. It is not a security fix by itself, but it removes a free hint from automated scanners.

Disable directory browsing

Without an index file, Apache may list a folder’s contents, and attackers love a free map of your plugins and uploads. One line fixes it:

Options -Indexes

If this line triggers a 500 error, your host does not allow the Options directive in .htaccess. Ask support to enable AllowOverride Options, or turn off directory indexes in the hosting panel instead.

Protect the wp-config.php file

The wp-config.php file holds your database credentials and secret keys. Normally the PHP handler executes it and returns a blank page, so the file is already safe. The rule in the “sensitive files” block above is defense in depth for the day PHP fails and Apache would otherwise serve the file as plain text. For stronger protection, WordPress also allows you to move wp-config.php one folder above the web root. The file is then not reachable by URL at all.

Restrict access to the WordPress admin area

If you always work from fixed IP addresses, create wp-admin/.htaccess and allow only those:

# wp-admin/.htaccess
<IfModule mod_authz_core.c>
  <RequireAny>
    Require ip 203.0.113.10
    Require ip 198.51.100.0/24
  </RequireAny>
</IfModule>

# Front-end features (WooCommerce, forms, search) call admin-ajax.php
<FilesMatch "^(admin-ajax|admin-post)\.php$">
  <IfModule mod_authz_core.c>
    Require all granted
  </IfModule>
</FilesMatch>

Do not skip the admin-ajax.php exception. Many themes and plugins, especially on WooCommerce stores, use it for visitor-facing actions, and blocking it quietly breaks cart fragments and live search. If your IP changes often, use password protection instead:

# Create the password file OUTSIDE the web root (SSH):
#   htpasswd -c /home/username/.htpasswds/wp-admin adminuser

# wp-admin/.htaccess
AuthType Basic
AuthName "Restricted area"
AuthUserFile /home/username/.htpasswds/wp-admin
Require valid-user

<FilesMatch "^(admin-ajax|admin-post)\.php$">
  Require all granted
</FilesMatch>

Locked yourself out? Connect by SFTP or File Manager, which do not depend on the web server rules, and rename wp-admin/.htaccess.

Block access to XML-RPC

xmlrpc.php is a legacy remote-publishing endpoint that attackers hammer with brute-force and amplification attempts. Block it unless you rely on the WordPress mobile app, Jetpack or a similar tool that still uses it:

<Files xmlrpc.php>
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
</Files>

Set custom error pages (404 and 403)

The ErrorDocument directive controls what visitors see on errors. For a 404, WordPress already serves your theme’s 404 template, so avoid overriding it. Use ErrorDocument for server-level errors that WordPress never gets to handle, such as a 403 from a blocked rule:

ErrorDocument 403 /error-403.html
ErrorDocument 500 /error-500.html

Use a relative path to a static HTML file. Pointing ErrorDocument at a full URL turns the response into a redirect and returns the wrong status code, which can confuse search engines. For the full syntax of these directives, the is worth bookmarking.

5. WordPress .htaccess Security Rules

The WordPress .htaccess security rules below reduce your attack surface, but they are one layer, not a complete defense. They cannot fix a vulnerable plugin, a weak password or malware that is already running. Treat them as hardening that sits alongside updates, backups and a firewall plugin.

Protect important configuration files

Beyond wp-config.php, sites accumulate forgotten files: database dumps, editor backups, .env files, logs. This pattern blocks dotfiles and the usual backup extensions in one go:

<FilesMatch "(^\.|\.(bak|old|orig|sql|log|swp|ini|env)$|~$)">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
</FilesMatch>

Apache’s default configuration already denies .htaccess and .htpasswd to web visitors, so the commonly repeated “protect .htaccess itself” rule is usually redundant. The pattern above is still useful because it covers files that Apache does not hide by default.

Block PHP execution in the uploads directory

This is one of the highest-value rules in the article. Uploads should hold images and documents, never executable code. If an attacker sneaks a PHP backdoor into wp-content/uploads, this rule stops it from running. Create wp-content/uploads/.htaccess:

# wp-content/uploads/.htaccess
<FilesMatch "(?i)\.(php|phtml|phar|php[3-8])$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
</FilesMatch>

Be careful with the same idea in wp-includes and wp-content. A blanket “deny all PHP” rule there breaks legitimate files such as the TinyMCE loader or plugin endpoints, and several tutorials still publish that mistake. The safer root-level alternative, adapted from the commonly used WordPress hardening recipe, blocks only known-sensitive paths. Place it above the WordPress block, and skip it on Multisite:

<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>

Prevent unauthorized access to sensitive files

Two more probes show up in almost every access log: author enumeration (?author=1, which reveals usernames) and image hotlinking, which eats bandwidth. Both have short fixes:

# Block ?author=N username scans
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} (^|&)author=\d+ [NC]
RewriteRule ^ - [F]
</IfModule>

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

Know the limits: the author rule does not stop username leaks through the REST API (/wp-json/wp/v2/users), so pair it with a security plugin or a REST restriction. Also, hotlink rules can block Google Images, social previews and RSS readers if you are too strict, so test them with the “allow empty referrer” line included.

Block suspicious requests and malicious bots

You can reject obviously malicious query strings and unwanted user agents before they ever reach PHP:

<IfModule mod_rewrite.c>
RewriteEngine On

# Script injection and base64 payloads in the query string
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} base64_(en|de)code\( [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|%[0-9A-Z]{0,2})
RewriteRule ^ - [F]

# Unwanted scrapers (replace the placeholders with agents from YOUR logs)
RewriteCond %{HTTP_USER_AGENT} (BadBot|ScrapeKit) [NC]
RewriteRule ^ - [F]
</IfModule>

Query-string filters can produce false positives, especially on sites with search or filter parameters, so watch your logs for a week after adding them. Remember too that user agents are trivially faked: .htaccess bot rules stop lazy scrapers, not determined attackers. A maintained firewall does that job better.

Add security headers using .htaccess

Security headers instruct the browser to enforce extra protections. This conservative set is safe for most WordPress and WooCommerce sites:

<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=()"

# Enable ONLY after every page and subdomain works over HTTPS
# Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>

Two notes on what is not in that list. X-XSS-Protection appears in many older guides but is obsolete, and modern browsers ignore it. A Content-Security-Policy header is valuable but needs careful testing, because payment gateways, analytics and page builders all inject scripts. Roll it out in report-only mode first.

Restrict access to specific IP addresses

To ban an abusive address or range, use Apache 2.4’s RequireAll container. This replaces the older Order allow,deny block that many guides still show:

<IfModule mod_authz_core.c>
  <RequireAll>
    Require all granted
    Require not ip 203.0.113.50
    Require not ip 198.51.100.0/24
  </RequireAll>
</IfModule>

IP bans are a stopgap, since attackers rotate addresses, and they can lock out real customers behind shared networks. For a broader checklist that includes passwords, updates and backups, work through our WordPress security checklist. And remember that no rule here replaces patching: when WordPress.org shipped in July 2026, it urged immediate updates and enabled forced auto-updates for affected sites. A hardened .htaccess cannot fix a vulnerable core.

6. WordPress .htaccess Performance Optimization

With a few directives you can shrink transfer sizes and let browsers reuse files they already downloaded. Treat these as a baseline: if you already run a caching plugin such as WP Rocket (see our WP Rocket review) or LiteSpeed Cache, it probably wrote equivalent rules inside its own marker block, and adding the same directives again just creates duplicates.

Enable GZIP compression

Compression shrinks text-based responses such as HTML, CSS, JavaScript and JSON by roughly 70 percent in typical cases, which means faster downloads on slow mobile connections.

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
AddOutputFilterByType DEFLATE application/javascript application/x-javascript application/json
AddOutputFilterByType DEFLATE application/xml application/rss+xml application/atom+xml
AddOutputFilterByType DEFLATE image/svg+xml font/ttf font/otf application/vnd.ms-fontobject
</IfModule>

Do not compress JPEG, PNG, WebP, AVIF or WOFF2 files, because they are already compressed and the extra CPU time buys nothing.

Configure browser caching

Browser caching tells returning visitors to reuse static files instead of downloading them again. mod_expires is the simplest way to set it:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"

# Never cache dynamic output
ExpiresByType text/html "access plus 0 seconds"
ExpiresByType application/json "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"

# Long-lived static assets
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/avif "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"

# CSS and JS: WordPress adds ?ver= to most files, but be cautious
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>

Set cache expiration headers

mod_expires sets the older Expires header and a matching max-age. For explicit control, or if mod_expires is unavailable, set Cache-Control directly with mod_headers:

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

Do not combine this with a second caching plugin that sets different lifetimes for the same file types. Conflicting headers are one of the most common reasons “cache settings do not stick.” After changing anything, open your browser’s developer tools, reload, and confirm the Cache-Control value on a CSS file.

Enable Keep-Alive connections

Keep-Alive lets a browser reuse one TCP connection for many requests instead of reconnecting for each file. Here is the honest answer that most tutorials skip: Keep-Alive is a server-level setting, and .htaccess cannot enable the KeepAlive directive. It lives in httpd.conf or the virtual host, and nearly every modern host already has it on:

# httpd.conf or virtual host (NOT .htaccess)
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

You will still see Header set Connection keep-alive recommended for .htaccess. It is a legacy HTTP/1.1 trick and does nothing useful on HTTP/2 or HTTP/3, where the Connection header is not used. If your host runs HTTP/2, skip it.

Optimize static file delivery

Correct MIME types and a default character set make sure modern formats load properly and text never shows garbled characters:

<IfModule mod_mime.c>
AddType image/webp .webp
AddType image/avif .avif
AddType font/woff2 .woff2
AddType image/svg+xml .svg .svgz
</IfModule>
AddDefaultCharset UTF-8

Combine these headers with properly sized images, a CDN and a lightweight theme for the best results. Static delivery rules cannot rescue a page that ships a megabyte of unused JavaScript.

Understand Brotli compression limitations

Brotli compresses text 15 to 25 percent smaller than GZIP at comparable speeds, so it is tempting to add it. Four limitations apply:

  • The mod_brotli module must already be loaded by the server. .htaccess cannot load modules.
  • Browsers only request Brotli over HTTPS.
  • Many hosts and CDNs (Cloudflare, for example) already apply Brotli at the edge, so enabling it twice is wasted effort.
  • Not every shared host compiles it in. Wrapping the rule in IfModule keeps the site safe when it is missing.
<IfModule mod_brotli.c>
AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/css text/javascript
AddOutputFilterByType BROTLI_COMPRESS application/javascript application/json image/svg+xml
</IfModule>

Keep the GZIP block as a fallback so visitors whose browsers do not send Brotli still get compressed responses.

7. WordPress .htaccess Redirect Rules

Redirects are the most common reason people open .htaccess. They preserve traffic and rankings when URLs change, but they also cause the most self-inflicted problems. The HTTPS and www rules in section 4 are the foundation; this section covers the rest of the toolkit.

Create 301 permanent redirects

Use a 301 when a URL has moved for good: a renamed post, a changed permalink structure, a deleted category. You already saw Redirect 301 and RedirectMatch. For redirects that depend on a query string, use rewrite conditions and end the target with ? to drop the old parameters:

# /?p=123  ->  /new-post/
RewriteEngine On
RewriteCond %{QUERY_STRING} ^p=123$
RewriteRule ^$ /new-post/? [R=301,L]

Create 302 temporary redirects

A 302 says “this move is temporary,” so search engines keep the original URL indexed. Use it for short-term campaigns, maintenance or A/B tests:

Redirect 302 /sale/ https://example.com/summer-sale/

Browsers cache 301 responses aggressively, sometimes for months. Always test a new rule as a 302 first, confirm it behaves, then switch it to 301.

Redirect HTTP to HTTPS and www to non-www

These are covered with copy-ready code in section 4. The key rule for redirect chains: each visitor should arrive at the final address in one hop. If http://www.example.com goes to https://www.example.com and then to https://example.com, you have a two-step chain that wastes time and dilutes signals. Check the real path with curl -I -L http://www.example.com/ and count the 301 lines.

Redirect an entire domain

When you move to a new domain, send every old URL to the same path on the new one so deep links survive:

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

Redirect specific pages and directories

To move a whole folder while keeping the rest of each URL, capture it in the regular expression:

# /shop-old/anything  ->  /shop/anything
RedirectMatch 301 ^/shop-old/(.*)$ https://example.com/shop/$1

# One page to another
Redirect 301 /about-us/ https://example.com/about/

Avoid redirect loops

A loop happens when rule A sends visitors to a URL that rule B sends back. Typical culprits: two HTTPS rules (one in .htaccess, one in a plugin), a CDN forcing HTTPS while the origin also redirects, or mismatched WordPress Address and Site Address values under Settings → General. The fix is always the same: keep one source of truth for each redirect, and test with curl rather than the browser, because the browser may serve a cached 301.

8. WordPress .htaccess Rules for Different Web Servers

Everything above assumes an Apache-compatible server. Your hosting stack decides what actually happens, so check before you paste.

Server Reads .htaccess? What to know
Apache Yes (if AllowOverride permits) The reference platform. All snippets here target Apache 2.4.
LiteSpeed Enterprise Yes Reads and applies most Apache directives, including rewrites, so existing rules usually work unchanged.
OpenLiteSpeed Partly Supports rewrite rules from .htaccess only when auto-load is enabled in the admin panel; other directives belong in the server configuration.
Nginx No Ignores the file completely. Rules must go into the server block.

Apache .htaccess configuration

On Apache, confirm two things before blaming your rules: that mod_rewrite is enabled, and that the virtual host contains AllowOverride All (or at least the groups you need) for your document root. On shared hosting you cannot change these yourself, but the support team can confirm them in minutes.

LiteSpeed server compatibility

LiteSpeed is the friendliest alternative to Apache for WordPress owners, because it loads .htaccess files and honors the same rewrite syntax. The LiteSpeed Cache plugin writes its own marker block into the file, so keep it intact. If you are comparing stacks, our Nginx vs LiteSpeed comparison breaks down the performance and compatibility trade-offs.

Why Nginx does not support .htaccess

Nginx was designed to read its configuration once at startup instead of checking every folder on every request. That is a big part of why it is fast, and it is also why .htaccess support was never added. If your host runs Nginx only (many managed WordPress hosts do), anything you place in .htaccess is silently ignored, and rules that appear to “do nothing” are usually the symptom. Ask your host whether rules go into a custom Nginx include or a panel setting.

Nginx equivalent configuration examples

These blocks go inside your site’s server { … } context. They mirror the most important Apache rules from this article. The explains the directives in detail.

# Pretty permalinks (the Nginx version of the WordPress default block)
location / {
    try_files $uri $uri/ /index.php?$args;
}

# Force HTTPS and a single canonical host (separate server block)
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}

# Block sensitive files and hidden files
location ~* /(wp-config\.php|xmlrpc\.php|readme\.html|license\.txt)$ { deny all; }
location ~ /\.(?!well-known) { deny all; }

# No PHP execution in uploads
location ~* ^/wp-content/uploads/.*\.php$ { deny all; }

# Compression and long browser cache for static files
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
location ~* \.(?:css|js|jpe?g|png|gif|webp|avif|svg|ico|woff2?)$ {
    expires 1y;
    add_header Cache-Control "public";
}

Nginx returns 403 for the blocked locations above, and directory listing is off by default, so there is no Options -Indexes equivalent to add. Reload with nginx -t && systemctl reload nginx, which tests the syntax before it applies the change.

9. Common WordPress .htaccess Errors and How to Fix Them

Almost every .htaccess failure falls into one of six families. Start with the same universal move: rename the file to .htaccess.off and reload the site. If the problem disappears, the fault is inside the file. If it does not, look elsewhere (PHP version, a plugin, file permissions).

Troubleshooting flow for a broken .htaccess fileFlowchart: rename .htaccess; if the site loads the fault is inside the file so restore the backup and add rules one at a time; if it still fails check logs, PHP and plugins.Site shows500 / 404 / loopRename .htaccessto .htaccess.offDoes thesite load?YESNOThe fault is in the fileRestore the backup, savepermalinks, then add rulesback one at a timeLook beyond .htaccessCheck the error log, PHPversion, plugins and filepermissions
Figure 4: The two-minute test that tells you whether .htaccess is really the culprit.

500 Internal Server Error

This is the classic .htaccess failure: Apache hits a line it cannot parse and refuses to serve anything. Common triggers are a typo, a stray character pasted from a web page, a directive your host does not allow, a missing module, and Apache 2.2 syntax on a 2.4 server. The server error log tells you exactly which line failed. Look for messages like these:

[core:alert] .htaccess: Invalid command 'php_value', perhaps misspelled or defined by
a module not included in the server configuration

[core:alert] .htaccess: Invalid command 'Order', perhaps misspelled or defined by
a module not included in the server configuration

The first message means php_value only works with mod_php; on PHP-FPM or FastCGI, set limits in .user.ini or your hosting panel instead (our guide to increasing the maximum upload size in WordPress shows each method). The second means you used legacy Order allow,deny access syntax; switch to Require as shown in this guide. For broader diagnosis, see our detailed walkthrough of the 500 Internal Server Error.

WordPress permalink not working

Symptoms: the homepage loads, but posts and pages return 404. Work through these in order:

  1. Go to Settings → Permalinks and click Save Changes.
  2. Check that .htaccess exists, contains the WordPress block, and is readable (644).
  3. Confirm mod_rewrite is enabled and AllowOverride is not set to None (ask your host).
  4. If you are on Nginx, remember .htaccess does nothing there. Use the try_files rule from section 8.

Too many redirects error

The browser reports ERR_TOO_MANY_REDIRECTS when two rules fight. Clear cookies, then check, in this order: a duplicate HTTPS rule in a plugin and in .htaccess; Cloudflare set to “Flexible” SSL while your origin also forces HTTPS (use Full or Full Strict); mismatched site and home URLs; and the www and non-www rules both enabled together. The X-Forwarded-Proto condition from section 4 resolves the proxy case.

403 Forbidden error

A 403 means Apache understood the request and deliberately refused it. After editing .htaccess, the usual suspects are an over-broad Require all denied pattern (such as a FilesMatch that also matches a legitimate file), a changed IP address after you restricted wp-admin, a missing admin-ajax.php exception, or file permissions that are too tight. Comment out recent rules one by one to find the offender.

Website showing a blank page

A blank page is typically a PHP fatal error, not an Apache one, but .htaccess can cause it indirectly: a php_value memory limit that is too low, or a blanket “deny PHP” rule that blocks a core file. Turn on logging in wp-config.php and read wp-content/debug.log:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

Changes to .htaccess not taking effect

  • Browser cache: a previous 301 may be cached. Test in a private window or with curl -I.
  • Server ignoring the file: AllowOverride None, Nginx, or OpenLiteSpeed without auto-load.
  • Wrong file: you edited a copy in a subfolder or on a different domain’s web root.
  • Cache layers: a page cache, CDN or host-level cache is still serving the old response. Purge them.
  • Rule order: an earlier rule with [L] is matching first. Move your rule higher.

10. Best Practices for Managing WordPress .htaccess

A little discipline turns .htaccess from a risky file into a dependable one. The most useful habit is to keep the file in a predictable order: security and redirects first, WordPress’s own block in the middle, performance and plugin blocks after it.

Recommended order of rules inside a WordPress .htaccess fileFour stacked sections from top to bottom: security blocks, canonical and custom redirects, the WordPress marker block that must not be edited, then performance and plugin-generated blocks.1. Security rules<FilesMatch …> Options -Indexes2. Redirects (HTTPS, www, 301s)RewriteCond … Redirect 301 …3. # BEGIN WordPress … # END WordPressManaged by WordPress. Never edit inside.4. Performance + plugin blocks# BEGIN WP Rocket mod_expires mod_deflateApache reads top to bottomWhy first?Block bad requests early.Why above WordPress?The catch-all rewrite wouldswallow later redirects.Hands offWordPress overwrites it.Safe to appendAdd caching and headers here.
Figure 5: A predictable layout makes the file easier to audit and safer to edit.
# ===== 1. SECURITY =====
Options -Indexes
# (FilesMatch blocks, author-scan block, etc.)

# ===== 2. REDIRECTS =====
# (HTTPS, www, custom 301s)

# BEGIN WordPress
# ... generated by WordPress, do not edit ...
# END WordPress

# ===== 3. PERFORMANCE =====
# (mod_deflate, mod_expires, Cache-Control headers)

# BEGIN WP Rocket
# ... written by the plugin ...
# END WP Rocket

Always back up before editing

Download a copy, or create a dated duplicate (.htaccess.bak-2026-12-03) before every change. For bigger edits, take a full site backup too. Backups turn a stressful outage into a thirty-second restore.

Test rules one at a time

Add a single rule, save, test the homepage and an inner page, then move on. If something breaks, you know exactly which line is responsible. Pasting twenty rules at once and debugging them together is how people lose an afternoon.

Avoid duplicate rewrite rules

Duplicate RewriteEngine On lines are harmless, but duplicate rules (two HTTPS redirects, two caching blocks) cause loops and conflicts. Search the file for https, ExpiresActive and AddOutputFilterByType before adding more.

Keep plugin-generated rules organized

Plugins write their rules between marker comments such as # BEGIN WP Rocket … # END WP Rocket, using the same mechanism WordPress itself uses (insert_with_markers()). Leave those blocks alone and put your own rules outside them. After you deactivate a plugin, check that its block was removed, because abandoned blocks sometimes stay behind.

Monitor server error logs

Your host’s error log is the fastest way to find a bad directive, and your access log shows which of your rules are firing. In cPanel, open Metrics → Errors; on a VPS, look in /var/log/apache2/error.log or /var/log/httpd/error_log. Check them after every change for the first day.

A short checklist you can keep next to your editor:

  • Downloaded the current .htaccess before editing
  • Added new rules outside the WordPress markers
  • Used Apache 2.4 Require syntax with an IfModule fallback
  • Tested the homepage, an inner page and wp-admin after each change
  • Checked redirects with curl -I -L, not only the browser
  • Kept file permissions at 644 and the file owned by your user
  • Searched for duplicate rules from plugins
  • Reviewed the error log the next day

If you want more examples to study, the sample .htaccess file on MDN is a well-commented reference for headers, MIME types and caching, but read each directive before copying it.

11. Frequently Asked Questions (FAQs)

Does WordPress need an .htaccess file?

Not strictly. WordPress runs fine without it, but only with “Plain” permalinks (?p=123). To use pretty permalinks on Apache or LiteSpeed, the rewrite block in .htaccess is required. On Nginx, the same job is done by a try_files rule in the server configuration.

Can I delete the WordPress .htaccess file?

You can, and WordPress will recreate its block the next time you save Settings → Permalinks, provided it can write to the folder. But everything custom in the file (redirects, security rules, cache settings) is lost, so rename or back it up instead of deleting.

Does .htaccess work with Nginx?

No. Nginx never reads .htaccess files. You must translate your rules into Nginx configuration, as shown in section 8, or use a hosting panel that exposes them as settings.

How do I regenerate WordPress .htaccess rules?

Go to Settings → Permalinks and click Save Changes, or run wp rewrite flush --hard with WP-CLI. Both rebuild the block between the # BEGIN WordPress and # END WordPress markers.

Can .htaccess improve WordPress security?

Yes, as one layer. Blocking PHP in uploads, hiding sensitive files, disabling directory listing and adding security headers all help. It does not replace updates, strong passwords, backups or a firewall, and it cannot clean existing malware.

Where should I add custom .htaccess rules?

Outside the WordPress markers. Put redirects and access blocks above # BEGIN WordPress so they run before the catch-all rewrite, and put caching or header rules below # END WordPress.

Does editing .htaccess affect SEO?

It can, in both directions. Correct 301 redirects, one canonical hostname, HTTPS and compression all support rankings and speed. Mistakes such as redirect chains, 302s used for permanent moves, loops, or accidental 403 and 500 responses can drop pages from search results quickly.

12. Final Thoughts

The WordPress .htaccess file rewards care more than cleverness. Keep WordPress’s own block intact, add one tested rule at a time, prefer Apache 2.4 syntax, and keep a dated backup within reach. Start with the high-value basics: a single HTTPS-and-hostname redirect, no PHP execution in uploads, sensitive files blocked, and sensible caching and compression. Skip the exotic rules you do not understand, because every line you add is a line you must maintain.

Finally, remember what this file is not. It cannot speed up a heavy theme, patch a vulnerable plugin or run on Nginx. Use it as the precise, low-level tool it is, alongside updates, backups and a good host, and you will rarely have to open it in a panic.

Inspire us with your love!

Saiful Islam

By Saiful Islam

Saiful Islam, the founder of aThemeArt, is a successful freelancer, a father of two boys, and an enthusiast in coding, YouTube, and gaming. Connect with me on Twitter, Facebook, and Instagram to stay updated with my latest endeavors.

You can check also

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*