WordPress redirect malware is one of the most frustrating infections because it often only affects certain visitors. Your site looks perfectly normal when you check it. But Google users, mobile visitors, or first-time visitors get sent to pharmaceutical spam, fake virus warnings, or adult content. The conditional nature of redirect malware means it can run for weeks or months before you even realize there is a problem, damaging your search rankings and your reputation with every redirected visitor.
This guide covers exactly where redirect code hides, how to find it, and how to remove it permanently. Every file path, command, and technique here comes from cleaning real WordPress redirect infections.
What Is WordPress Redirect Malware?
Redirect malware is malicious code injected into your WordPress site that intercepts incoming requests and sends visitors to attacker-controlled websites. The attacker profits from the redirected traffic through advertising revenue, affiliate fraud, phishing credential harvesting, or drive-by malware downloads on the destination site.
Most redirect malware is conditional. It does not redirect every visitor every time. That would be too obvious. Instead, it uses targeting rules to avoid detection:
- Search engine referral only: The redirect triggers only when visitors arrive from Google, Bing, or Yahoo. Direct visits and bookmarks load your site normally. This targets your highest-value traffic.
- Mobile devices only: The malware checks the User-Agent header and redirects only mobile browsers. Desktop visitors, including you checking your site from your office computer, see nothing wrong.
- First visit only: A cookie is set after the first redirect. Subsequent visits from the same browser load normally. You visit your site once, get redirected, visit again, and everything looks fine. It seems like a one-time glitch.
- Admin exclusion: The malware detects WordPress admin cookies and never redirects logged-in administrators. You literally cannot see the problem while logged into your own site.
- Geographic targeting: Some variants redirect only visitors from specific countries, often targeting regions where the attacker’s monetization scheme is most profitable.
These conditions explain why site owners frequently say “it works fine for me” while their visitors, customers, and Google are experiencing something completely different.
Where Redirect Code Hides
Redirect malware can inject itself into five primary locations within a WordPress installation. A thorough cleanup requires checking all five.
.htaccess File
The .htaccess file in your WordPress root directory is the most common location for redirect malware. It processes every incoming request before WordPress even loads, making it the most efficient place to intercept traffic.
Look for RewriteRule directives you did not create, especially those containing Base64-encoded strings, external URLs, or conditions based on HTTP_REFERER (targeting search engine visitors) or HTTP_USER_AGENT (targeting mobile devices). The malicious rules are sometimes inserted between the standard WordPress rewrite rules, making them easy to overlook at a glance.
Also check for .htaccess files in subdirectories. Attackers create separate .htaccess files in wp-content/, wp-content/uploads/, and even deep within plugin directories. A find / -name ".htaccess" -type f command on your server reveals every .htaccess file across the entire installation.
wp-config.php
The wp-config.php file loads before any WordPress code executes, giving injected code maximum control. Redirect malware in wp-config.php typically appears as an eval() call with a Base64-encoded payload near the top of the file, before the database credential definitions.
The injected code may also appear as a require_once or include statement that loads a separate malicious PHP file. Check for any include statements that reference files outside standard WordPress directories, files with random-character names, or files in the wp-content/uploads/ directory (which should never contain PHP files that get included by wp-config.php).
Theme functions.php
The wp-vcd malware family specifically targets the functions.php file of every installed theme. It inserts a require_once call at the very beginning of the file, before any existing code or comments. This call loads a malicious file, often named something like wp-content/themes/starter/starter.php or wp-includes/wp-vcd.php, which handles the actual redirect logic.
Check functions.php in every installed theme, not just your active theme. wp-vcd infects all themes because switching themes would otherwise disable the malware. Open each file and examine the first 5 to 10 lines for any code that was not part of the original theme, particularly require_once statements pointing to files with generic or random names.
JavaScript Injection
Client-side redirects use JavaScript rather than PHP. The malicious script typically gets injected into header.php or footer.php of your active theme, either as inline script blocks or through hijacked wp_enqueue_script calls that load external JavaScript files.
Look for <script> tags in your theme template files that you did not add. The JavaScript is usually obfuscated using character code arrays, string concatenation, or encoding functions. A common pattern creates a hidden iframe or uses window.location to redirect the browser after a short delay. The delay makes the redirect appear as if the page loaded normally and then “broke.” Check header.php, footer.php, and index.php in your active theme.
Database
Database-stored redirects are the hardest to find because no file scanning tool detects them. Two database tables are primary targets.
wp_options table: Check the siteurl and home options. If either value has been changed to a different domain, every link WordPress generates points to the attacker’s site. Also check for injected JavaScript in widget content stored in widget_text or widget_custom_html option entries. Malicious autoloaded options with encoded payloads execute PHP code on every page load.
wp_posts table: Malicious JavaScript injected into post_content fields executes when visitors view affected posts or pages. The injected script may appear at the end of the content, after a large block of whitespace designed to push it below the visible area in the WordPress content editor. Check with this WP-CLI command:
wp db query "SELECT ID, post_title FROM wp_posts WHERE post_content LIKE '%<script%src=%' AND post_status='publish';" --allow-root
Step-by-Step Redirect Malware Removal
1. Confirm the Redirect
Verifying the redirect exists and understanding its trigger conditions determines where to look for the malicious code.
Test in incognito/private browsing mode. Open a new incognito window and visit your site through a Google search result (search for site:yourdomain.com and click a result). Incognito mode eliminates admin cookies that would suppress the redirect.
Test with different referrers. Use a browser extension or curl command to set the HTTP referrer to Google:
curl -L -A "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)" -e "https://www.google.com/" https://yourdomain.com/
This command simulates a mobile visitor arriving from Google. If the redirect is referrer-based and mobile-targeted, the curl output will show a 301 or 302 redirect to the attacker’s site.
Run a Sucuri SiteCheck scan. Visit sitecheck.sucuri.net and scan your domain. SiteCheck detects many common redirect malware variants and shows the redirect chain if one is found.
Check Google Search Console. The Security Issues section may already have flagged the redirect. The Coverage report may show redirect chains for your indexed pages that point to unexpected destinations.
2. Back Up Your Site First
Create a complete backup of files and database before making any changes. Use WP-CLI for the database export and tar/zip for files. You need this backup as a safety net and for forensic analysis.
wp db export /tmp/pre-cleanup-backup.sql --allow-root
tar -czf /tmp/pre-cleanup-files.tar.gz /path/to/wordpress/
3. Check .htaccess
Open the .htaccess file in your WordPress root directory. The default WordPress .htaccess should contain only the standard permalink rewrite rules between # BEGIN WordPress and # END WordPress markers. Remove everything outside those markers that you did not add yourself.
Search for these specific red flags: any line containing base64 or eval, RewriteCond lines referencing HTTP_REFERER with Google or other search engines, RewriteCond lines checking HTTP_USER_AGENT for mobile browsers, and RewriteRule directives pointing to external domains.
If the .htaccess is heavily modified and you are not sure what is legitimate, replace it entirely with the WordPress default and then regenerate your permalinks from Settings > Permalinks in the WordPress admin.
Check for additional .htaccess files in subdirectories:
find /path/to/wordpress/ -name ".htaccess" -type f
4. Check wp-config.php
Open wp-config.php and carefully review every line. The file has a well-defined structure: PHP opening tag, optional code, database settings, authentication keys, table prefix, debug settings, and the “That is all, stop editing” comment followed by the require statement for wp-settings.php.
Remove any eval() calls, base64_decode() calls, or require_once/include statements that reference files you do not recognize. Pay special attention to code added before the database credential section, as this is where most wp-config.php injections are placed.
Verify that DB_HOST, DB_NAME, DB_USER, and DB_PASSWORD match your hosting provider’s actual database credentials. Attackers occasionally change these to point your site at their own database.
5. Scan All Theme and Plugin Files
Use grep to search for the most common malicious PHP function patterns across your entire wp-content directory:
grep -rl "eval(base64_decode" /path/to/wordpress/wp-content/
grep -rl "str_rot13" /path/to/wordpress/wp-content/
grep -rl "gzinflate" /path/to/wordpress/wp-content/
grep -rl "preg_replace.*\/e" /path/to/wordpress/wp-content/
The -rl flags list only the filenames containing matches, giving you a clean list of files to inspect. Open each flagged file and determine whether the matched code is legitimate plugin functionality (rare for these patterns) or malware (far more likely).
Examine functions.php in every theme:
head -20 /path/to/wordpress/wp-content/themes/*/functions.php
This shows the first 20 lines of each theme’s functions.php, which is where wp-vcd and similar malware inserts its loader code. For more scanning approaches, our comparison of WordPress malware removal plugins reviews the best automated scanning tools available.
6. Check the Database
Verify your site URLs have not been modified:
wp option get siteurl --allow-root
wp option get home --allow-root
Both values should return your actual domain. If either shows a different domain, correct it immediately:
wp option update siteurl "https://yourdomain.com" --allow-root
wp option update home "https://yourdomain.com" --allow-root
Search for injected JavaScript in post content:
wp db query "SELECT ID, post_title, LEFT(post_content, 200) FROM wp_posts WHERE post_content LIKE '%<script%' AND post_content NOT LIKE '%youtube%' AND post_content NOT LIKE '%twitter%' AND post_status='publish' LIMIT 20;" --allow-root
This query finds published posts containing script tags while filtering out common legitimate embeds. Review each result carefully. If you find widespread JavaScript injection across many posts, a targeted SQL UPDATE statement is more efficient than editing each post individually.
Check wp_options for large autoloaded entries that could contain malware payloads:
wp db query "SELECT option_name, LENGTH(option_value) as size FROM wp_options WHERE autoload='yes' ORDER BY size DESC LIMIT 20;" --allow-root
Abnormally large autoloaded options (over 50KB) that you do not recognize by name are potential malware storage locations.
7. Replace WordPress Core Files
After cleaning all identified malware from theme, plugin, and database locations, reinstall WordPress core to ensure no core file tampering remains:
wp core download --force --allow-root
This replaces wp-admin/ and wp-includes/ with verified clean copies from wordpress.org without touching wp-content/ or wp-config.php.
Reinstall your plugins from clean sources:
wp plugin install your-plugin-name --force --allow-root
For detailed instructions on the full reinstallation process, our complete WordPress malware removal guide covers every step from core file replacement through plugin reinstallation.
8. Harden Against Reinfection
Redirect malware gets in through a vulnerability. Cleaning without patching the vulnerability guarantees reinfection. Take these steps immediately after cleanup:
- Update WordPress core, all plugins, and all themes to latest versions
- Delete inactive themes and plugins entirely (not just deactivated, fully deleted)
- Set file permissions to 644 for files and 755 for directories
- Disable PHP execution in
wp-content/uploads/by adding deny rules to its .htaccess - Change all passwords: WordPress admin, FTP/SFTP, database, hosting panel
- Regenerate WordPress authentication keys and salts in wp-config.php
- Install Wordfence or Sucuri for ongoing monitoring and file integrity checking
Why Redirect Malware Keeps Coming Back
The number one reason redirect malware returns after cleanup is a missed backdoor. Attackers do not rely on a single point of persistence. A typical redirect malware infection includes the visible redirect code (what you found and cleaned) plus one or more hidden backdoor scripts that recreate the redirect code if it is removed.
Backdoors hide in locations that are easy to overlook. Common hiding spots include PHP files in wp-content/uploads/ with innocuous names like wp-content/uploads/2025/01/social-icons.php, modified core files in wp-includes/ that pass casual inspection, mu-plugins in wp-content/mu-plugins/ (a directory many site owners do not know exists), and database-stored PHP code that gets written to a file and executed via a cron job.
The backdoor typically checks every few hours whether the redirect code is still in place. If it has been removed, the backdoor reinstalls it. This is why you can clean redirect malware at 2 PM and find it back at 8 PM. You removed the symptom but not the persistence mechanism.
Breaking this cycle requires finding and removing every backdoor, not just the redirect code. Search for PHP files that create or modify other PHP files:
grep -rl "file_put_contents" /path/to/wordpress/wp-content/
grep -rl "fwrite" /path/to/wordpress/wp-content/
Legitimate plugins use these functions, so not every match is malicious. But a file in the uploads directory or a file with a random name that writes to other PHP files is almost certainly a backdoor.
When to Call a Professional
Redirect malware that keeps returning after cleanup usually means a backdoor is hiding somewhere your scans and manual inspection missed. This is not a failure on your part. Sophisticated attackers deliberately place backdoors in locations that resist standard cleanup procedures.
Professional help makes sense when the redirect returns within hours or days of each cleanup attempt, when you have found and cleaned multiple malicious files but the redirect persists, when the infection affects multiple sites on the same server, or when your business loses revenue and customer trust with every day the problem continues.
Our WordPress malware removal team handles persistent redirect infections with manual code review and backdoor forensics. Every cleanup includes identification and removal of all redirect code and associated backdoors, a detailed incident report documenting the attack vector and all compromised files, security hardening to prevent reinfection through the same vulnerability, and a reinfection guarantee. If you need to understand the full scope of a WordPress malware infection beyond just redirects, our step-by-step malware removal guide covers the complete process.