
You delete the infected plugin, restore the theme, reset every password, and the redirect to a casino is still there. Or the site is clean when you open it and hijacked when a customer clicks it in Google. When the usual fixes do not stick, the code is often not in WordPress at all. It sits in two small configuration files that run before WordPress: .htaccess and .user.ini. This guide shows what malicious rules in them look like, how they hide, how to find them in ten minutes, how to clean them, and what Security by CleanTalk can and cannot see in these files.
In brief
- .htaccess (Apache) and .user.ini (PHP running as CGI/FastCGI, including PHP-FPM) are per-directory configuration files. They are applied on every request and are not part of WordPress core, so a core file check passes straight over them.
- Attackers use them for four things: redirects only for visitors from Google, running a payload before every PHP script (auto_prepend_file), making image files execute as PHP, and letting only their own backdoor file through.
- They are hidden with blank lines, by placing rules outside the WordPress markers, with file names that imitate WordPress files, and sometimes with an immutable flag that makes deletion fail.
- Deleting the loaded PHP file is not enough: the directive that loads it stays, and so do copies in subdirectories.
- The fix is to find every .htaccess and .user.ini, remove the directive and the file it loads, then close the entry point.
Why attackers like server configuration files
A configuration file gives an attacker control without touching a single WordPress file. wp core verify-checksums and similar tools compare core against known hashes, and .htaccess and .user.ini are not in core. The files run before WordPress, so the logic fires even if you deactivate every plugin. And both names start with a dot, so file managers and SFTP clients often hide them.
Two limits are worth knowing. .htaccess only works on Apache-compatible servers where AllowOverride permits it; Nginx ignores it completely. .user.ini only works when PHP runs as CGI/FastCGI or PHP-FPM, and PHP re-reads it only every 5 minutes by default (user_ini.cache_ttl is 300 seconds), so a change can take a few minutes to show up. The PHP manual describes the scan: PHP checks each directory from the requested script up to the document root.
Five tricks to look for
1. Redirects only for visitors from search
The classic. The rule checks the HTTP referrer and sends the visitor to a spam site only when they come from a search engine:
RewriteEngine On
RewriteCond %{HTTP_REFERER} (google|bing|yahoo|duckduckgo)\. [NC]
RewriteCond %{HTTP_USER_AGENT} !(bot|crawl|spider) [NC]
RewriteRule ^ https://spam-example.invalid/landing [R=302,L]
You type your address directly, so there is no referrer and you see the normal site. A crawler is excluded by the user-agent condition, so search engines index a clean page. Only real visitors from Google are redirected. Google classes this as a spam practice called sneaky redirects. Variants add conditions for mobile browsers, a country, or a cookie, so the redirect fires once per person.
2. Image files that execute as PHP
A few lines make the web server treat harmless-looking extensions as PHP:
AddHandler application/x-httpd-php .jpg .png
<FilesMatch "^cache-img\.jpg$">
SetHandler application/x-httpd-php
</FilesMatch>
The handler name depends on the host, but the idea is constant. A file called cache-img.jpg in wp-content/uploads passes upload filters and file-type checks, yet runs code when it is requested. This is why blocking PHP execution in the uploads directory matters — see our guide on disabling PHP execution in WordPress uploads.
3. A payload before every PHP script: auto_prepend_file
auto_prepend_file tells PHP to run another file before every PHP script, and auto_append_file runs one after. It is a legitimate directive with a documented mode (PHP_INI_PERDIR), which is exactly why it can be set in both places:
# .htaccess (works with mod_php only)
php_value auto_prepend_file "/home/user/public_html/wp-content/uploads/.cache/wp-sync.php"
# .user.ini (PHP-FPM / FastCGI)
auto_prepend_file = /home/user/public_html/wp-content/uploads/.cache/wp-sync.php
The effect is severe. The file runs on wp-login.php, on wp-admin and on every other script, so it can read submitted passwords, inject spam into output, or accept commands, while WordPress core, the theme and the plugins stay byte-for-byte clean. The directive works like a require: if you delete the loaded file first, PHP fails on every request and the whole site goes down.
4. Rules that protect the backdoor
Access rules can shield the attacker’s own file and blind scanners that fetch other files over HTTP:
<FilesMatch ".*">
Require all denied
</FilesMatch>
<Files "wp-sync.php">
Require all granted
</Files>
Everything in the directory returns 403 except the backdoor. A new .htaccess in a directory such as wp-content/uploads or wp-includes that denies everything and allows one file is a strong indicator.
5. How the code stays hidden
- Blank lines. The rules are pushed below dozens of empty lines, so the file looks like three lines of boilerplate in a narrow editor window. Scroll down, or use wc -l.
- Outside the WordPress markers. WordPress rewrites only the section between # BEGIN WordPress and # END WordPress when you save permalinks. Lines above or below survive that, and a "regenerate permalinks" cleanup leaves them in place.
- Imitation names. The files they load are named like core files: wp-sync.php, wp-cache.php, class-wp-session.php, often in hidden or cache-like directories such as .cache or wp-content/uploads/2024/05.
- Immutable flag. On Linux an attacker with enough rights can set the immutable attribute (chattr +i), and then even the owner gets "Operation not permitted" when deleting the file.
- Many copies. The same files are dropped into dozens of directories, so removing one leaves the rest.
Signs that your site is affected
- Visitors from Google land on another site, while a direct visit looks fine.
- A .htaccess or .user.ini exists in a directory where you never created one — wp-content/uploads, wp-includes, wp-admin, a plugin directory.
- An .htaccess is much larger than the default WordPress block, or has content after # END WordPress.
- Deleting a file fails with "Operation not permitted", or the file returns after you delete it. The second case is covered in how cron re-infects WordPress.
How to check in ten minutes
Start from outside, then look on the server. Compare what a direct visitor and a visitor from Google receive:
curl -sI https://yourdomain.com/ | grep -i -E "^(HTTP|location)"
curl -sI -e "https://www.google.com/" -A "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)" https://yourdomain.com/ | grep -i -E "^(HTTP|location)"
A Location: header in the second answer and not in the first is a referrer-based redirect. Then, over SSH in the site root, list every configuration file, search it for suspicious directives, and look for the immutable flag:
find . \( -name ".htaccess" -o -name ".user.ini" -o -name "php.ini" \) -exec ls -l {} \;
grep -rniE "auto_prepend_file|auto_append_file|php_value|AddHandler|SetHandler|HTTP_REFERER|HTTP_USER_AGENT" --include=.htaccess --include=.user.ini --include=php.ini .
find . -type f -mtime -30 -name ".*" -ls
lsattr -R . 2>/dev/null | awk '$1 ~ /i/'
Read each hit in full, past the blank lines. A default WordPress .htaccess contains none of these directives, so any match deserves an explanation. Be careful with one exception: some hosts set auto_prepend_file or a .user.ini themselves, and a firewall plugin can legitimately load a file this way, so verify where the file it points to comes from before deleting it. With no shell access, use your host’s file manager with Show hidden files enabled.
Meet Security by CleanTalk
Security by CleanTalk is a free WordPress security plugin that combines a malware scanner with signature and heuristic analysis and auto-cure, a File System Watcher, a cloud firewall, brute-force protection and 2FA. The cloud service behind it costs $9 per year after the trial.
For this specific threat, it helps to know exactly what the plugin looks at. The Malware Scanner analyzes PHP, HTML and JavaScript files and PHP-like extensions such as phtml and phar. It does not parse the directives inside .htaccess or .user.ini, so the commands above remain the way to find a rule itself. What the plugin does give you:
- It finds the payload. The file loaded by auto_prepend_file is PHP, so the scanner flags it by signature or heuristics like any other loader, and it will find a web shell in uploads that the rules were protecting.
- It will not break your site while curing. The scanner’s delete action refuses to remove a file that the running PHP configuration lists in auto_prepend_file or auto_append_file, because deleting it would crash every request. You first remove the directive, then the file.
- It checks permissions. It reports unsafe permissions on a short list of files, including .htaccess, index.php and wp-config.php, and recommends 644 for those files and 755 for the core directories.
- It blocks PHP in uploads. The setting Disable PHP execution in uploads folder writes its own block into wp-content/uploads/.htaccess, which blocks direct execution of uploaded PHP files on Apache. A deeper .htaccess in a subdirectory can override it, so keep checking for stray .htaccess files.
- It reports the new PHP files. The File System Watcher records added and changed .php files, so a payload dropped into a random directory shows up as a new file. It does not record edits to .htaccess itself — see our guide to file integrity monitoring.
How to scan and clean
1. Install the plugin and add the access key
In the admin, go to Plugins → Add New, search for Security by CleanTalk, then Install Now and Activate.

Open Settings → Security by CleanTalk → General Settings and click Get access key automatically.

2. Run a scan and turn on upload protection
Open the Malware Scanner tab and click Perform Scan. Review Critical and Suspicious first, and look at the paths: a PHP file with a core-like name in uploads or in a hidden directory is the usual target of a prepended payload.

Then enable Disable PHP execution in uploads folder in the settings, so a leftover file in uploads cannot run even if the scan misses it.
Clean up completely
Do these in order, because the pieces depend on each other:
- Back up first — the whole site, including hidden files — and keep a copy of the logs.
- Replace the site-root .htaccess with the default WordPress block, and remove everything outside the # BEGIN WordPress and # END WordPress markers unless you added it yourself.
- Remove every .user.ini you did not create, and every extra .htaccess in subdirectories. If deletion fails, run lsattr on the file and, with the right access, chattr -i it, or ask your host.
- Delete the file the directive loaded only after the directive is gone, then run the scanner again to look for siblings of that file.
- Check the admin users and the database for accounts and options you did not create — see our article on major signs of malware.
- Rotate every credential — WordPress admins, database, hosting, SFTP — and change the salts. Our guide to forcing logout with Shuffle Salts covers the last part.
- Close the entry point. Update the plugin or theme that was exploited, and review who has access. A cleaned site with the same hole is reinfected within days.
- Recheck from outside with the curl commands, and wait five minutes after changing .user.ini, because PHP caches it.
Alternative ways to find and fix this
Config files fall between tools: many scanners read only code. Feature sets change, so check each vendor’s current documentation before relying on this table.
| Approach | What it covers | Strengths | Limits |
|---|---|---|---|
| Manual search over SSH | Every .htaccess, .user.ini and php.ini | Reads the exact directives; no plugin | Needs shell access and care |
| Search Console URL Inspection | What Google receives for a URL | The authoritative view of Googlebot | Does not show a visitor-only redirect |
| Security by CleanTalk | PHP/HTML/JS files, permissions, uploads protection, new PHP files | Finds payload and shells; blocks PHP in uploads | Does not read .htaccess directives |
| Other WordPress security plugins | Code scanners and firewalls | Wide rule sets | Verify whether they inspect config files |
| Server-level integrity tools (for example AIDE) | Any file that changes | Catches config edits | Needs root access and setup |
Frequently asked questions
Where is the .htaccess file in WordPress, and why can’t I see it?
It sits in the site root, next to wp-config.php. Its name starts with a dot, so file managers and SFTP clients hide it by default. Turn on Show hidden files, or run ls -la over SSH. A site can have several: plugins and attackers both create .htaccess files in subdirectories.
Does .htaccess malware work on Nginx?
The .htaccess rules do not: Nginx ignores the file. But the same attacker has a second route. .user.ini works with PHP-FPM and FastCGI on Nginx too, and the PHP payload it loads runs wherever PHP does. Nginx sites should check .user.ini and the web server’s own configuration.
What does auto_prepend_file do, and is it always malicious?
It runs a PHP file before every script. It is a normal directive, and some hosts and firewall plugins use it on purpose. It is malicious when it points to a file you cannot account for, especially one in uploads, a cache directory or a hidden folder. Check where the file came from before you remove either one.
I removed the redirect lines, but they came back. Why?
Something rewrites the file: a copy in another directory, a scheduled task, a backdoor that restores it, or a compromised account that logs in again. Find the process, not just the lines. Check cron, other .htaccess files and the admin list, and rotate credentials.
Why can’t I delete my .htaccess file?
Either the permissions or ownership block you, or the immutable attribute is set. Run lsattr on the file; an i in the flags means immutable, and chattr -i clears it with the right access. If you do not have root, ask your host, because an immutable flag you did not set is itself a sign of compromise.
Can a security plugin detect malicious .htaccess rules?
It depends on the plugin. Scanners that analyze only code files will not read directives. Security by CleanTalk’s scanner does not parse .htaccess or .user.ini, but it finds the PHP payload they load, warns about unsafe permissions on .htaccess, and blocks direct PHP execution in uploads. Use a manual search for the rules themselves.
Key takeaway
The most persistent WordPress infections hide where WordPress does not look: two small configuration files that run first and are skipped by every core check. Search every .htaccess and .user.ini, read past the blank lines, remove the directive and then the file it loads, and always close the way in. Keep file monitoring on afterwards, so a new PHP file in a strange place is the first thing you hear about.
Sign up for CleanTalk — free trial — malware scanning with auto-cure, file integrity monitoring, firewall, brute-force protection and 2FA for your WordPress site.