WordPress htaccess Guide: Common Configurations for Security, Speed, and Control

Introduction

The .htaccess file is one of those files that WordPress site owners tend to either ignore completely or break something trying to edit. It sits in your root directory and controls how Apache serves your site. For WordPress specifically, it handles permalink rewriting, security rules, caching headers, and redirects. This wordpress htaccess guide covers the practical configurations you are most likely to need, with exact code examples and clear explanations of what each block does. Whether you are a site owner trying to lock things down or a developer looking for a reference, this guide gives you usable, tested snippets — not theory.

A WordPress htaccess file opened in a code editor showing rewrite rules and security directives in the root directory

What Is the .htaccess File and Why Does It Matter?

The name stands for “hypertext access,” but that tells you next to nothing. What matters is what it does. It is a per-directory configuration file for Apache web servers. When Apache serves a request for a directory, it checks for a .htaccess file in that directory and applies the rules it finds there.

For WordPress, the most critical job of .htaccess is URL rewriting. When you set your permalinks to something other than the default “plain,” WordPress writes a block of rewrite rules into .htaccess. Without those rules, your pretty URLs break, and visitors see 404 errors on every page except the homepage.

Beyond rewriting, .htaccess is used for:

  • Security restrictions (blocking access to sensitive files)
  • Redirects (301 and 302)
  • Browser caching (expires headers)
  • Compression (Gzip)
  • Blocking bad bots
  • Preventing hotlinking

The file lives in your WordPress root directory, which is usually the public_html folder or a subfolder depending on your installation. It is hidden by default because of the leading dot, so you may need to enable “show hidden files” in your FTP client to see it.

Back Up Your Existing .htaccess File First (Critical Step)

Do not skip this. Editing .htaccess without a backup is the fastest way to take your site down. A single typo, a missing closing bracket, or a forgotten RewriteEngine On can trigger a 500 Internal Server Error that makes your entire site inaccessible.

Here is how to back it up properly:

  • Via FTP: Connect to your server, navigate to the root directory, and download the .htaccess file to your local computer. A reliable FTP client makes this process easy and secure.
  • Via cPanel File Manager: Open File Manager, find .htaccess in public_html, right-click, and download.

Keep a copy with a clear name like .htaccess.bak.2024-10-01. If something goes wrong, you can rename the broken file to something like .htaccess.broken and rename your backup back to .htaccess. This restores your site instantly.

A common beginner mistake is editing the file directly on the server without a backup, then not being able to undo the change because the site is already returning errors. The extra minute it takes to download a copy is cheap insurance.

Essential Security Configurations for .htaccess

Security through .htaccess is fast because it happens at the server level, before WordPress even loads. These rules add useful barriers against common attack vectors.

Block Directory Browsing

By default, if someone navigates to a directory on your site that does not have an index file, Apache lists all the files in that directory. This reveals your folder structure and file names, which helps attackers. Add this line:

Options -Indexes

Place it near the top of the file, above the WordPress rewrite block.

Protect wp-config.php

This file contains your database credentials and secret keys. It should never be accessible from the web. Add this to block direct access:

<Files wp-config.php>
    order allow,deny
    deny from all
</Files>

Block Access to wp-includes

The wp-includes folder contains core WordPress files that should never be accessed directly by a browser. This rule blocks most direct requests to that folder:

RewriteRule ^wp\-includes/(.*) - [F,L]

This returns a 403 Forbidden status for any request that hits wp-includes directly.

Limit Access to wp-admin by IP

If you are the only person logging into your site, you can restrict the admin area to your IP address. Add this above the WordPress section:

# Allow only specific IP to access wp-admin
order deny,allow
deny from all
allow from YOUR_IP_ADDRESS

Replace YOUR_IP_ADDRESS with your actual IP. This works well for single-user sites but does not work for sites with multiple admins or dynamic IPs.

Block Suspicious User Agents

Some bots and scrapers are malicious. Blocking them by user agent string is imperfect (they can change it), but it helps reduce load from known bad actors:

RewriteCond %{HTTP_USER_AGENT} ^.*(badiucao|cegabot|dotbot|heritrix|purebot|scrapy|curl|wget).*$ [NC]
RewriteRule .* - [F,L]

Prevent Hotlinking

Hotlinking means other sites embed your images directly, using your bandwidth. This rule blocks that:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yoursite\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F]

Replace yoursite.com with your domain.

A note on security: .htaccess rules are a first layer, not a complete solution. Pair them with a dedicated security plugin like Wordfence or Sucuri for active monitoring, firewall, and malware scanning. These plugins handle what .htaccess cannot: application-level threats and login brute force attempts. For additional protection, consider a web application firewall that adds a further layer of defense.

A digital lock icon over a WordPress server dashboard with security and backup settings

Common WordPress Rewrite Rules (Permalinks and More)

When you update your permalinks in WordPress admin (Settings → Permalinks), WordPress writes a default rewrite block to .htaccess. It looks like this:

# BEGIN WordPress
<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

That block is standard and should remain in place for WordPress to function.

301 Redirects for Moved Pages

The most common custom rule is a permanent redirect from an old URL to a new one. Use Redirect 301 for simple cases:

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

Put this above the WordPress section.

Remove Trailing Slashes

Some people prefer URLs without trailing slashes. This rule removes them:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

Note the check for directories. If the request matches a real directory, the rule is skipped to avoid issues.

Add Trailing Slashes

The reverse is also common for consistency:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R=301]

www vs non-www Redirect

Choose one and redirect the other:

# Force www
RewriteCond %{HTTP_HOST} ^yoursite\.com [NC]
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [L,R=301]

Or the reverse:

# Remove www
RewriteCond %{HTTP_HOST} ^www\.yoursite\.com [NC]
RewriteRule ^(.*)$ https://yoursite.com/$1 [L,R=301]

For complex redirect scenarios, especially those involving wildcards or conditional logic, consider a plugin like Redirection. It gives you a GUI, logs redirects, and tracks 404s. But for simple, one-off redirects, .htaccess is faster and cleaner.

Caching and Performance Tweaks via .htaccess

Browser caching tells visitors’ browsers to store static files locally so they do not have to download them again on repeat visits. This is done with Expires headers.

<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType text/javascript "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/gif "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/woff "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>

This sets a one-year cache for static assets and a one-month default for everything else.

Gzip Compression

Gzip compresses files before sending them to the browser, reducing bandwidth usage and load times:

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

The Tradeoff

Heavy caching can cause issues during site updates. If you have a long cache duration for CSS and your theme changes, returning visitors may see broken layouts until their cache refreshes. Use versioned filenames (e.g., style.css?v=2) or a cache-busting mechanism. Most caching plugins handle this automatically.

For many sites, a CDN like Cloudflare handles caching more intelligently and is easier to manage through a dashboard than raw .htaccess rules. If you are already using a performance plugin like W3 Total Cache or WP Super Cache, it may also manage .htaccess cache rules for you. Test your configuration with a tool like GTmetrix or PageSpeed Insights to verify the headers are being sent correctly.

Blocking Bad Bots and Scrapers

If your server load is high and you see strange user agents in your logs, bad bots are likely the cause. A practical .htaccess blocklist can help:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (ahrefsbot|mj12bot|dotbot|semrushbot|buzzsumo|exabot) [NC]
RewriteRule .* - [F,L]

You can add more user agent strings to the list separated by the pipe character. Be careful not to block legitimate search engine crawlers like Googlebot or Bingbot — that will hurt your SEO.

The best approach is to monitor your server logs or use a tool like Matomo or a security plugin to identify which bots are consuming resources before you start blocking. Blocking blind can cut off traffic you did not realize was useful.

For persistent bot problems, a combination of .htaccess rules and a web application firewall (WAF) from a service like Cloudflare or Sucuri gives better protection with less maintenance.

Redirecting with .htaccess: 301, 302, and Regex Patterns

Understanding when to use 301 vs 302 matters for SEO. A 301 redirect passes most of the original page’s link equity to the new URL. A 302 redirect does not — it indicates the move is temporary.

Simple 301 Redirect

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

Simple 302 Redirect

Redirect 302 /temporary-page/ https://yoursite.com/other-page/

Redirect an Entire Old Domain

RewriteCond %{HTTP_HOST} ^olddomain\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.olddomain\.com [NC]
RewriteRule ^(.*)$ https://newdomain.com/$1 [L,R=301]

Regex-Based Redirects

More powerful but also more dangerous. For example, redirect all URLs with a query parameter to a clean URL:

RewriteCond %{QUERY_STRING} ^page_id=123$
RewriteRule ^index\.php$ /new-url/? [R=301,L]

The trailing question mark in the destination tells Apache to strip the query string.

Another example: change a URL pattern from /category/post-name/ to /blog/post-name/:

RewriteRule ^category/(.*)$ /blog/$1 [R=301,L]

Test regex patterns on a staging site first. A poorly written regex can create infinite loops, where the redirect keeps redirecting to itself until the browser times out. Also avoid chaining redirects (A → B → C). Each hop loses some link equity and slows the user experience. Point everything directly to the final URL.

If your redirect logic gets complex — more than a handful of rules — use a plugin like Redirection. It prevents you from creating loops and gives you an audit log.

Common Troubleshooting: 500 Internal Server Errors and White Screen of Death

A 500 Internal Server Error is the most common result of a broken .htaccess file. The error can be a generic white screen or a specific page with the error code.

How to Fix It

  1. Connect via FTP or cPanel File Manager.
  2. Rename the current .htaccess file to .htaccess.broken.
  3. Upload your backup or create a fresh, minimal .htaccess with just the WordPress rewrite rules.
  4. Refresh your site. If it loads, your original file had the error.

Common Causes

  • Missing RewriteEngine On: Without this, no rewrite rules work.
  • Unclosed blocks: Every <IfModule or <Files tag needs a matching closing tag.
  • Syntax errors: A missing space or typo in a regex pattern.
  • Conflicting rules: Two rules that contradict each other can produce an unexpected 500.

The fix is almost always straightforward: rename, restore, and test. Once the site is back, you can debug the broken file in a text editor locally before uploading again.

When to Use .htaccess vs. a Plugin or Server Config

There is no single right tool for every situation. Here is how to decide.

.htaccess Is Best For

  • Simple, permanent redirects (a few rules)
  • Security rules that block access to specific files or directories
  • Cache-control headers (if you are comfortable with headers)
  • Server-level performance rules (Gzip, expires)

.htaccess is fast because it runs before WordPress loads. But it is error-prone, especially for non-developers. A single mistake can take your site offline.

Plugins Are Best For

  • Complex redirect management with logging and 404 tracking
  • Caching configuration with a GUI (W3 Total Cache, WP Super Cache)
  • Security monitoring and firewall rules that adapt dynamically (Wordfence, Sucuri)
  • Any situation where you want an audit trail or rollback capability

Plugins add overhead because they load within WordPress, but they also provide safety nets and interfaces that reduce the chance of breaking something. Beginners may want a WordPress security plugin to manage these settings through a dashboard.

Server Config (httpd.conf or vhost) Is Best For

  • Rules that apply to all sites on a server
  • Performance-critical rules that should not be in the web root
  • Shared hosting environments where .htaccess is limited

If you are on shared hosting, you usually cannot edit httpd.conf. But some hosts offer a “Web Application Firewall” or “Security Rules” section in cPanel that does similar things. Check your host’s documentation.

If you are a site owner with minimal development experience, use a plugin for anything complex and only use .htaccess for the one or two rules you absolutely need. If you are a developer comfortable with server config, use .htaccess for performance and security, but test everything on a staging site first.

What Not to Do: Common .htaccess Mistakes

These mistakes are common enough that I have seen each one more than once in live production sites.

  • Not using full paths in redirects. A redirect to /new-page on yoursite.com works, but if you are redirecting to a different domain, you must include the full URL including https://.
  • Forgetting to test redirects. A redirect loop that works on your local machine may cause a 500 on your server. Always test the final URL.
  • Leaving outdated rules. If you remove a plugin that wrote rules into .htaccess, those rules remain and can cause errors. Clean up the file after deactivating plugins that modify it.
  • Copying code from random forums without understanding it. Many .htaccess snippets floating around are incomplete or designed for specific setups that do not match yours.
  • Ignoring file permissions. .htaccess should be set to 644 on most servers. If the file is not readable by Apache, your rules will not apply, but you also may not see errors.
  • Editing with the wrong line endings. If you edit on Windows and upload via FTP in ASCII mode, line endings can break. Use a proper text editor like VS Code, Sublime Text, or Notepad++.

A staging site is your best friend for testing .htaccess changes. If you do not have one, consider setting one up or at least testing changes during low-traffic hours.

A WordPress staging environment open in a browser with development tools and code editor visible

Next Steps: Protecting Your Entire WordPress Site

This guide covered the most useful .htaccess configurations for security, performance, and redirects. But .htaccess is just one piece of a larger maintenance picture.

A solid site management routine includes:

  • Regular automated backups (offsite)
  • Security audits (at least quarterly)
  • Performance monitoring (check load times and server resources)
  • Core, theme, and plugin updates

If managing all of this yourself feels like too much, managed WordPress maintenance services handle the grunt work — including .htaccess configuration, security hardening, and performance tuning — so you can focus on running your site. It is worth considering if your time is better spent elsewhere.

Similar Posts