Starter Offer: WordPress Malware Cleanup From $89 Claim on WhatsApp →

WordPress Malware Removal

Professional cleaning and security hardening for just

WordPress .htaccess Malware: The Complete Guide to Every Type (With Real Code Samples)

MD Pabel December 6, 2025
AI Summary
WordPress .htaccess Malware: The Complete Guide to Every Type (With Real Code Samples)

WordPress .htaccess malware is any malicious modification to your site’s .htaccess configuration file (or fake .htaccess files planted in subdirectories) that lets an attacker control how your server responds to requests. Real-world .htaccess malware does one of about ten specific things: blocks PHP execution to lock you out, hides backdoors behind allowlists, redirects search-engine or mobile traffic to spam sites, cloaks SEO injections, hijacks default file handlers, restricts admin access by IP, or in rare cases executes attacker-controlled PHP through cookie data. Cleaning it requires identifying which pattern hit your site, replacing the malicious file with a clean .htaccess, and — critically — finding the dropper script or backdoor that placed it there, because .htaccess malware almost always returns within hours if you skip that step.

Quick Answer: What you need to know about WordPress .htaccess malware

  • What it is: malicious rules added to your real .htaccess, or fake .htaccess files dropped into subdirectories
  • What it does: blocks PHP, redirects traffic, cloaks spam from Google, allowlists backdoor files, or hijacks how your server handles requests
  • Why it keeps coming back: there’s almost always a dropper script (a PHP backdoor) that recreates the malicious .htaccess after deletion
  • How to actually fix it: identify the pattern, replace with a clean .htaccess, then hunt the dropper script and close the original entry point
  • What to watch for: lookalike filenames (wp-l0gin.php), FilesMatch rules you didn’t write, conditional RewriteRule directives, and .htaccess files in folders that shouldn’t have one

If your WordPress site has started redirecting visitors to spam pages, your dashboard is throwing a 403 Forbidden error, your search rankings are suddenly polluted with Japanese or pharmaceutical keywords, or your hosting account has been flagged for malware — there’s a strong chance the .htaccess file is involved.

In more than 4,500 hacked WordPress site cleanups since 2018, I’d estimate .htaccess manipulation appears in roughly 7 out of 10 cases. Sometimes it’s the entire attack. More often, it’s one component in a larger compromise — a multiplier that makes other malware harder to detect and remove.

This guide is the comprehensive map of how .htaccess malware actually works. I’ll walk through every major pattern I see in the wild, show you real code samples for each, and link out to deeper case-study posts where they exist. By the end, you’ll be able to look at any .htaccess file on your server and know whether it’s clean, compromised, or somewhere in between.


What .htaccess Actually Is (And Why Hackers Love It)

.htaccess is a configuration file used by Apache web servers to control how the server handles requests for files in a given directory. WordPress relies on it for permalinks. Your hosting provider may use it for redirects, security headers, or compression rules. It’s a powerful, flexible tool — and that’s exactly why attackers target it.

Here’s what makes .htaccess uniquely valuable to a hacker:

  • It runs before WordPress does. Apache reads .htaccess rules before any PHP code executes. So .htaccess-based attacks fire before your security plugin has a chance to react.
  • It applies to whole directories at once. A single rule can affect every file in a folder and every subfolder beneath it. That’s why a single infected .htaccess can lock out a whole site.
  • It’s text-based and small. Easy to inject through any vulnerability that allows file writes, easy to hide from owners who don’t know what their .htaccess should contain.
  • It’s often overlooked. Most site owners have never opened their .htaccess file. They wouldn’t recognize a malicious rule if they saw one.
  • It’s not PHP. Most malware scanners are tuned to look for malicious PHP. Suspicious Apache directives often slip through with no flags raised.

A hacker who can write to your .htaccess can effectively reconfigure your web server. That’s a lot of power from a 200-byte text file.


The 10 Types of WordPress .htaccess Malware I See Most Often

Across thousands of cleanups, the malicious .htaccess patterns I encounter cluster into about ten distinct types. Each one has a different purpose, a different visual signature, and (sometimes) a different fix.

Type 1: PHP Execution Lockout (The Admin Block)

The attacker drops an .htaccess file inside /wp-admin/ or your site root that blocks PHP files from running:

<FilesMatch "\.(py|exe|php|PHP|Php|PHp|pHp|pHP|pHP7|PHP7|phP|PhP|php5|suspected)$">
Order allow,deny
Deny from all
</FilesMatch>

Because your WordPress login page (wp-login.php) and admin scripts are PHP files, this rule produces a 403 Forbidden error when you try to log in. The casing variations (PhP, pHp, etc.) are deliberate — attackers cover every possible filesystem behavior to make sure the rule fires.

A clean WordPress install does not have an .htaccess file inside /wp-admin/. If yours does, treat it as malicious until proven otherwise.

Deeper coverage: I broke down every variant of the lockout pattern, including IP-based, user-agent, and basic-auth versions, in why a 403 Forbidden error on wp-admin could be a malicious htaccess hack.

Type 2: Backdoor Allowlist (The Selective Block)

A more aggressive evolution of Type 1. Instead of just blocking PHP, the attacker pairs the denial with an allowlist of their own backdoor filenames:

<FilesMatch "\.(py|exe|phtml|php|PhP|php5|suspected)$">
Order Allow,Deny
Deny from all
</FilesMatch>
<FilesMatch "^(class-t\.api\.php|index\.php|doc\.php|hh\.php|wp-blog\.php|wp-l0gin\.php|lock360\.php)$">
Order allow,deny
Allow from all
</FilesMatch>

The allowlist contains a mix of legitimate-looking names (index.php) and obvious backdoors disguised with character substitutions or random short names (hh.php, doc.php, wp-l0gin.php with a zero, lock360.php).

This pattern is especially common on shared hosting where the same .htaccess ends up duplicated across hundreds of folders. I documented one real example with 1,162 infected files across a single account in this Bluehost case study.

Type 3: Search-Engine Conditional Redirect

Probably the most damaging type from a business perspective. The rule redirects visitors only when they arrive from a search engine, leaving direct visitors and the site owner seeing a normal site:

RewriteEngine On
RewriteCond %{HTTP_REFERER} (google|bing|yahoo|duckduckgo) [NC]
RewriteRule .* https://spam-target.example/landing [R=302,L]

This is why so many owners are blindsided when they discover the infection. They visit their own site directly — it works fine. They check it from another browser — fine. But every visitor coming from Google search results is being silently redirected to a scam, casino, or pharmacy site. The first sign is usually a Google Safe Browsing flag, a drop in conversions, or a confused customer email.

Deeper coverage: see how hackers hide redirects in htaccess and why your WordPress site is redirecting to spam.

Type 4: Mobile-Only Traffic Hijacking

The same redirect technique, but conditional on the user’s device:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (android|iphone|ipad|mobile) [NC]
RewriteRule .* https://malicious-mobile.example/ [R=302,L]

Mobile visitors get redirected; desktop visitors don’t. This is brutally effective because the site owner — usually viewing the site on a desktop — never sees the issue. Customers report it. Owners assume the customer is wrong.

Deeper coverage: the case study in finding a mobile redirect hack using access logs walks through exactly this scenario.

Type 5: SEO Spam Cloaking (Japanese / Pharma Hack)

A specific type of .htaccess rule used in Japanese keyword hacks and pharmaceutical SEO spam injections. The rule serves different content to Googlebot than to human visitors:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (Googlebot|Bingbot) [NC]
RewriteRule ^(.*)$ /spam-injection-handler.php?url=$1 [L]

When Google crawls the site, it sees thousands of spam pages full of pharmaceutical or Japanese-language keywords. When a human visits any of those URLs, they see the normal site (or a redirect). The result is your domain ranking for spam terms in Google while looking clean to you.

Deeper coverage: the complete guide to the Japanese keyword hack and how to stop pharmaceutical spam in Google.

Type 6: IP Allowlist Backdoor

Subtle and often misread as legitimate hardening:

Order Deny,Allow
Deny from all
Allow from 203.0.113.45

Anyone hitting wp-admin gets 403, except the attacker’s IP. To a casual visual scan, this looks like a security rule a previous developer might have added. If you see an IP allowlist in your /wp-admin/ .htaccess and you don’t recognize the IP, treat it as a backdoor — not a hardening measure.

Type 7: Cookie-Based PHP Execution

The rare and dangerous case where an attacker actually makes your .htaccess execute PHP. By default, .htaccess can’t run PHP — but if a server is misconfigured to treat .htaccess as a PHP file (via AddHandler or AddType abuse), an attacker can plant code like this:

AddType application/x-httpd-php .htaccess
<?php $c = $_COOKIE; ... include($k); ?>

The PHP payload reads attacker-supplied cookies, reconstructs function names from them dynamically, and writes/executes a backdoor on the fly. It’s a sophisticated pattern that bypasses most signature scanners because no recognizable malicious function names appear in the file.

Deeper coverage: cookie-based PHP backdoor in htaccess explained and the broader analysis in obfuscated PHP malware detection.

Type 8: AddHandler / AddType Abuse

A more general version of Type 7 — abusing handler directives so that files with innocent-looking extensions execute as PHP:

AddType application/x-httpd-php .jpg
AddHandler x-httpd-php .gif

After this, an image file uploaded to wp-content/uploads/ can execute as PHP code when requested. The attacker uploads a “photo” that’s actually a backdoor. I covered the broader pattern of malware hidden in image files in how malware hides in GIF files on WordPress and can a JPG file contain malware.

Type 9: DirectoryIndex Hijacking

A small directive change with a massive effect:

DirectoryIndex hack.php index.php

This tells Apache: “when someone visits a folder, serve hack.php first if it exists.” The attacker uploads hack.php somewhere in your site and now controls what every visitor sees on that path. The original index.php still exists, untouched — which makes this hard to spot during a quick file review.

Type 10: ErrorDocument Abuse

The attacker redirects 404 (and sometimes 403) errors to malicious destinations:

ErrorDocument 404 https://malicious.example/landing.html

Every broken link on your site, every typo in a URL, every test request from a security scanner — all of it sends visitors to the attacker’s page. Because most site owners never deliberately trigger a 404 on their own site, this can run undetected for months.


Less Common But Real .htaccess Malware Variants

Beyond the ten main types, I occasionally see:

  • Geographic redirects using mod_geoip rules — visitors from specific countries get redirected, others don’t
  • Hotlink-protection abuse — instead of protecting your images, the rules redirect external image requests to malicious resources
  • Header injection via Header set directives — adds malicious tracking, ads, or cryptomining JavaScript via HTTP headers
  • Encoding manipulation using AddEncoding or SetEnv to alter how content is served
  • Conditional SetEnvIf rules that combine with PHP-side checks to deliver different malware to different visitors

These aren’t rare because they don’t work — they’re rare because the easier patterns above achieve most of what attackers want without the complexity.


How to Detect .htaccess Malware on Your Site

Before you can clean anything, you have to find it. The detection methods I rely on, in order:

1. Visual review of every .htaccess file on the server

A clean WordPress install only needs .htaccess files in two places: the site root (for permalinks) and inside wp-content/uploads/ in some configurations (with a single Deny from all line on certain hosts). Anywhere else, especially in /wp-admin/, /wp-includes/, individual plugin or theme folders, or wp-content/uploads/ beyond the host’s defaults — that’s worth investigating.

2. Find every .htaccess file at once

Over SSH or your hosting terminal, run:

find . -name ".htaccess" -type f

This lists every .htaccess on the account. Compare it to what should exist. On a typical single-WordPress-install Bluehost or SiteGround account, you should see one — maybe two. Hundreds is a clear sign of recursive infection.

3. Check modification dates

find . -name ".htaccess" -type f -newer /tmp -printf "%T+ %p\n"

Sort by date and look for .htaccess files that were modified recently — especially close to the time you first noticed symptoms.

4. Pattern-grep for known malicious directives

Common strings to grep for across all .htaccess files:

  • FilesMatch with multiple PHP casing variations
  • HTTP_REFERER with search engine names
  • HTTP_USER_AGENT with mobile device names
  • AddType or AddHandler applied to non-PHP extensions
  • RewriteRule directives pointing to external domains
  • Allow from with a single specific IP

5. Use a security scanner — but don’t rely on it alone

Wordfence, Sucuri, MalCare, and your hosting provider’s malware scanner can flag known patterns. They miss plenty. Treat scanner results as a starting point, not a verdict.

For a broader malware detection workflow that covers PHP, JavaScript, and database-side infections, see how to detect WordPress malware.


Step-by-Step .htaccess Malware Cleanup

Once you’ve identified malicious .htaccess rules, the cleanup follows a strict order. Skipping steps is how cleanups fail.

1. Take backups before changing anything

Download the entire site (files + database) before deleting or modifying. Save the malicious .htaccess files separately as evidence — they often contain clues (filenames, IP addresses, redirect targets) that help you find related backdoors.

2. Replace your root .htaccess with a clean default

Don’t just delete it — WordPress needs the root .htaccess for permalinks. Replace the contents with:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

3. Delete .htaccess files that shouldn’t exist

Any .htaccess inside /wp-admin/, /wp-includes/, individual plugin/theme folders, or non-default subdirectories — delete them. WordPress doesn’t need them.

4. Regenerate clean rewrite rules

Inside WordPress: Settings → Permalinks → Save Changes. This forces WordPress to rebuild its .htaccess rules cleanly.

5. Hunt the dropper

This is the step that determines whether the cleanup holds. The malicious .htaccess didn’t appear by itself — a PHP script wrote it. That script is still on your server. Until you find and remove it, the malicious .htaccess will reappear within minutes to hours.

I cover the common dropper patterns in detail in why WordPress malware keeps coming back.

6. Audit users, cron jobs, and the database

Hidden admin accounts, scheduled malicious cron tasks, and database-stored payloads are the second-tier persistence mechanisms. See how to find and remove hidden admin users and scanning your WordPress database for hidden malware.

7. Rotate every credential

WordPress admin, hosting cPanel, FTP/SFTP, the database user, and any email address that received password resets during the compromise. Also rotate WordPress security keys (the salts in wp-config.php) to invalidate active sessions.


Why .htaccess Malware Keeps Coming Back

If you’ve cleaned the malicious .htaccess three times in a week and it keeps reappearing, you have a persistence problem — not a cleanup problem. The most common reasons:

  • A dropper script. Usually a PHP file disguised as a plugin, theme file, or fake core file (wp-l0gin.php, doc.php, radio.php) that recreates the .htaccess on every page load or every cron tick.
  • A scheduled WordPress cron task. The infection registers itself as a recurring cron job, so even removing the dropper doesn’t help if the cron entry is still in the database.
  • Hidden admin users. If an attacker still has admin access, they re-upload everything you remove.
  • The original entry-point vulnerability. An outdated plugin, weak password, or nulled theme that lets the attacker walk back in any time they want.
  • Backdoors elsewhere in the codebase. Especially obfuscated PHP shells in uploads, plugin folders, or wp-includes. If even one of these survives cleanup, the infection reproduces.

The cleanup is not finished when the visible symptom (the .htaccess) is gone. It’s finished when none of the persistence mechanisms above are still active.


How to Prevent .htaccess Malware From Coming Back

Once you’re clean, hardening prevents the next infection. The steps with the highest impact:

  • Update WordPress core, plugins, and themes promptly. Most .htaccess infections trace back to a known plugin vulnerability that had a patch available.
  • Remove nulled or pirated plugins/themes. A frighteningly high percentage ship with backdoors pre-installed — see why nulled plugins and themes are a security disaster.
  • Use strong, unique admin passwords with two-factor authentication. Both on WordPress and on your hosting cPanel.
  • Disable PHP execution in uploads/. Add a directive that blocks .php file execution inside wp-content/uploads/. This single change blocks a huge percentage of upload-based attacks.
  • Restrict file permissions. Your .htaccess file should typically be 644, your folders 755, your files 644. Anything writable by the world is a risk.
  • Run a web application firewall (WAF). Wordfence, Sucuri, Cloudflare WAF, or your host’s built-in firewall — they all reduce the attack surface significantly.
  • Monitor file changes. Get alerted whenever .htaccess changes or new PHP files appear in places they shouldn’t.
  • Keep off-host backups. Backups stored on the same server as the site can be infected along with everything else.

For a complete hardening walkthrough, see how to secure a WordPress site and the more focused how to secure your WordPress login.


Frequently Asked Questions About .htaccess Malware

Can a .htaccess file itself be a virus?

Not in the traditional sense — .htaccess is a configuration file, not an executable script. But it can issue server-level instructions that cause significant harm: blocking your access, redirecting visitors to malware, or hijacking how files are served. The file isn’t the virus. It’s the weapon a hacker uses against you.

How do I know if my .htaccess is hacked?

The clearest signs: visitors being redirected to spam (especially from Google), 403 Forbidden errors when you try to log in, Search Console reporting “Site hacked” warnings, antivirus tools blocking your domain, or finding .htaccess files in folders that shouldn’t have them (like /wp-admin/). Manually opening every .htaccess on your server and reading it is the fastest definitive check.

Why does my .htaccess malware come back every time I delete it?

Because there’s a dropper script — a malicious PHP file somewhere on your server — that recreates the malicious .htaccess automatically. You’re cleaning the symptom, not the source. Find and remove the dropper (and audit users, cron jobs, and the database for related persistence) before declaring the site clean.

Can .htaccess malware redirect only certain visitors?

Yes — and this is the most damaging variant for businesses. Conditional rules can redirect only visitors arriving from search engines, only mobile users, only specific countries, or only visitors using specific browsers. The site owner sees a normal site; the visitors don’t. This is why so many .htaccess infections are discovered via customer complaints rather than direct observation.

What’s the difference between malicious .htaccess rules and legitimate ones a developer added?

Legitimate rules are usually well-commented, follow Apache best practices, and serve a clear functional purpose (permalinks, security headers, redirects to your own pages). Malicious rules typically lack comments, contain redirect targets to unfamiliar domains, reference filenames you’ve never created, or block file types your site uses. When in doubt, ask whoever maintains the site (or audit it line by line).

Should I just delete every .htaccess file on my account to be safe?

No. Your root .htaccess is required for WordPress permalinks. Some plugins and hosting setups also use .htaccess files in specific subdirectories. The safe approach is to identify which files are malicious and clean those specifically, then regenerate the legitimate root file via WordPress permalinks settings.

How quickly can .htaccess malware do damage?

Within minutes. A search-engine redirect can start costing you traffic the moment Googlebot crawls a hijacked page. A Google Safe Browsing flag can land within hours of detection. SEO damage from cloaking attacks (Japanese hack, pharma hack) can take months to fully recover from. The cost of waiting to clean is much higher than the cost of cleaning.


Need Expert Help With a .htaccess Malware Cleanup?

.htaccess malware is fixable in most cases, but the cleanups that succeed are the ones where every persistence layer is removed — not just the visible symptom. Removing the malicious .htaccess without finding the dropper, the backdoor users, the cron tasks, and the original entry point is the single most common reason these infections return.

If your WordPress site has been hit by any of the patterns covered above, your hosting account has been flagged or suspended, or you’ve already tried cleaning the .htaccess and the malware came back, this is exactly the kind of recovery I do every week. I’ve cleaned more than 4,500 hacked WordPress sites since 2018.

Get Expert WordPress Malware Removal

Explore Our Security Services

About the Author

MD Pabel

MD Pabel

MD Pabel is the Founder and CEO of 3Zero Digital, a leading agency specializing in custom web development, WordPress security, and malware removal. With over 8+ Years years of experience, he has completed more than 3200+ projects, served over 2300+ clients, and resolved 4500+ cases of malware and hacked websites.

Read Next