
WordPress Redirect Hack: How to Detect and Remove It
The WordPress redirect hack is one of the most frustrating infections for site owners. Your site appears to work perfectly when you visit it directly, but your users get redirected to phishing pages, fake tech support scams, or pharmaceutical spam sites. In 2026, this attack remains among the most widespread because it is extremely profitable for hackers: every redirect generates revenue through malicious ad networks. This guide walks you through how to detect, diagnose, and completely remove a redirect hack on WordPress, step by step.
How to fix a WordPress redirect hack (7 etapes)
- 1
Confirm the redirect hack — Test your site in incognito mode via a Google search to verify the malicious redirect triggers.
- 2
Identify the redirect type — Determine whether the hack uses .htaccess injection, database modification, PHP, or JavaScript.
- 3
Reset the .htaccess file — Replace your .htaccess with a clean WordPress default and write-protect the file.
- 4
Clean the database — Remove malicious scripts from wp_posts and suspicious entries from wp_options.
- 5
Scan and clean PHP files — Search all PHP files for eval, base64_decode, and gzinflate patterns and remove infected code.
- 6
Reinstall WordPress core — Download a fresh copy of WordPress and replace wp-admin, wp-includes, and root PHP files.
- 7
Harden security — Change all passwords, regenerate security keys, and install a web application firewall.
What Is a WordPress Redirect Hack
A redirect hack is an attack where malicious code is injected into your WordPress site to automatically redirect visitors to third-party websites. Unlike other malware types, the redirect hack is often conditional: it only triggers under certain circumstances, making it particularly difficult to detect.
Malicious redirects can be inserted into:
- The .htaccess file at the site root
- The WordPress database (
wp_options,wp_poststables) - PHP files in core, themes, or plugins
- The wp-config.php file
- JavaScript files loaded dynamically
The goal is always the same: monetize your traffic by sending visitors to sites the hacker controls or that pay a commission per visit.
Types of WordPress Redirect Hacks
Understanding the type of redirect you are dealing with is essential for knowing where to find the malicious code. Here are the 4 main types encountered in 2026.
1. .htaccess Injection
This is the most classic type. The hacker inserts redirect rules directly into the .htaccess file:
# Example of malicious .htaccess code
RewriteEngine On
RewriteCond %{HTTP_REFERER} .*google.* [OR]
RewriteCond %{HTTP_REFERER} .*bing.* [OR]
RewriteCond %{HTTP_REFERER} .*facebook.*
RewriteRule ^(.*)$ http://malicious-site.com/redirect [R=302,L]This method is particularly insidious because it only redirects visitors coming from search engines or social media. The site owner, who accesses the site directly via URL, sees nothing abnormal.
2. wp_options Redirect
The hacker modifies the siteurl or home values in the wp_options table, or injects malicious JavaScript into options like widget_text:
-- Check siteurl and home values
SELECT option_name, option_value
FROM wp_options
WHERE option_name IN ('siteurl', 'home');3. JavaScript Redirect
JavaScript code is injected into theme files, posts, or widgets to redirect on the client side:
// Typical malicious code (obfuscated)
var _0x4f2a = ["\x68\x74\x74\x70\x3A\x2F\x2F"];
if (document.referrer.indexOf("google") !== -1) {
window.location.href = _0x4f2a[0] + "malicious-site.com";
}4. Conditional PHP Redirect
This is the most advanced form. PHP code is injected into wp-config.php, functions.php, or wp-load.php and executes redirects based on complex conditions:
// Example of conditional redirect
if (isset($_SERVER['HTTP_USER_AGENT']) &&
preg_match('/bot|crawl|spider/i', $_SERVER['HTTP_USER_AGENT']) === 0 &&
!isset($_COOKIE['visited'])) {
setcookie('visited', '1', time() + 86400);
header('Location: http://malicious-site.com');
exit();
}This code only redirects real visitors (not bots), and only once (using a cookie), making detection by automated tools nearly impossible.
How to Diagnose a Redirect Hack
Before cleaning, you need to confirm the infection and identify its source. Here is a systematic diagnostic process.
Step 1: Test in Incognito Mode
Open an incognito browsing window and access your site via a Google search (type site:yoursite.com in Google, then click a result). Many redirect hacks only trigger when the visitor arrives from a search engine.
Step 2: Simulate Different User-Agents
Use curl to test with different referrers and user-agents:
# Test with a Google referrer
curl -L -A "Mozilla/5.0" -e "https://www.google.com" https://yoursite.com -o /dev/null -w "%{url_effective}
"
# Test with a mobile user-agent
curl -L -A "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)" https://yoursite.com -o /dev/null -w "%{url_effective}
"
# Compare with direct access
curl -L -A "Mozilla/5.0" https://yoursite.com -o /dev/null -w "%{url_effective}
"If the effective URL differs between tests, you have confirmed a conditional redirect.
Step 3: Inspect the .htaccess File
# Display the full .htaccess contents
cat /path/to/wordpress/.htaccess
# Search for suspicious redirect rules
grep -n "RewriteRule\|Redirect\|RedirectMatch" /path/to/wordpress/.htaccessA standard WordPress .htaccess file contains only these rules:
# 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 WordPressAny other RewriteRule with an external URL is suspicious.
Step 4: Check wp-config.php
# Look for suspicious includes or redirects in wp-config.php
head -20 /path/to/wordpress/wp-config.php
# Search for base64-encoded code
grep -n "base64_decode\|eval(\|gzinflate\|str_rot13" /path/to/wordpress/wp-config.phpMalicious code is often inserted before the first <?php line or after the require_once ABSPATH . 'wp-settings.php'; line.
Step 5: Scan the Database
-- Search for malicious JavaScript in posts
SELECT ID, post_title
FROM wp_posts
WHERE post_content LIKE '%<script%'
AND post_content LIKE '%location%';
-- Search for redirects in wp_options
SELECT option_name, LEFT(option_value, 200) AS value_preview
FROM wp_options
WHERE option_value LIKE '%eval(%'
OR option_value LIKE '%base64_decode%'
OR option_value LIKE '%document.location%'
OR option_value LIKE '%window.location%';
-- Verify site URLs
SELECT option_name, option_value
FROM wp_options
WHERE option_name IN ('siteurl', 'home', 'template', 'stylesheet');Step 6: Use Scanning Tools
| Tool | Type | Command / URL |
|---|---|---|
| WP-CLI | Command line | wp plugin verify-checksums --all |
| Wordfence | WordPress plugin | Scan from dashboard |
| Sucuri SiteCheck | Online | sitecheck.sucuri.net |
| Google Safe Browsing | Online | transparencyreport.google.com |
| VirusTotal | Online | virustotal.com |
Step-by-Step Cleanup
Once the diagnosis is complete, proceed with the cleanup in this precise order. Make a full backup before starting.
Step 1: Reset the .htaccess File
# Back up the infected .htaccess for analysis
cp /path/to/wordpress/.htaccess /path/to/wordpress/.htaccess.infected
# Replace with a clean .htaccess
cat > /path/to/wordpress/.htaccess << 'EOF'
# 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
EOF
# Write-protect the file
chmod 444 /path/to/wordpress/.htaccessAlso check .htaccess files in subdirectories (/wp-content/, /wp-includes/, /wp-admin/). Some hacks create additional .htaccess files:
# Find all .htaccess files
find /path/to/wordpress/ -name ".htaccess" -type fStep 2: Clean the Database
-- Remove malicious scripts from posts
-- WARNING: run a SELECT first to verify
UPDATE wp_posts
SET post_content = REGEXP_REPLACE(
post_content,
'<script[^>]*>.*?(location|redirect|window\\.location).*?</script>',
''
)
WHERE post_content REGEXP '<script[^>]*>.*?(location|redirect|window\\.location).*?</script>';
-- Remove suspicious options added by malware
DELETE FROM wp_options
WHERE option_name NOT IN (
SELECT option_name FROM (
SELECT option_name FROM wp_options
WHERE autoload = 'yes'
AND option_name LIKE 'wp_%'
) AS safe_options
)
AND option_name LIKE '%redirect%'
AND option_name NOT LIKE '%woocommerce%';
-- Check for unauthorized admin accounts
SELECT ID, user_login, user_email, user_registered
FROM wp_users
WHERE ID IN (
SELECT user_id FROM wp_usermeta
WHERE meta_key = 'wp_capabilities'
AND meta_value LIKE '%administrator%'
);Delete any administrator account you do not recognize.
Step 3: Clean PHP Files
# Search for malicious code in all PHP files
grep -rn "eval(base64_decode\|eval(gzinflate\|eval(str_rot13" /path/to/wordpress/
# Find PHP files in the uploads folder (should not exist)
find /path/to/wordpress/wp-content/uploads/ -name "*.php" -type f
# Reinstall WordPress core
wp core download --force --skip-content
# Reinstall all plugins from wordpress.org
wp plugin install $(wp plugin list --field=name --format=csv) --force
# Reinstall the active theme
wp theme install $(wp theme list --status=active --field=name) --forceStep 4: Clean wp-config.php
# Compare with a clean wp-config-sample.php
diff /path/to/wordpress/wp-config.php /path/to/wordpress/wp-config-sample.php
# Check the first and last lines (hackers' preferred locations)
head -5 /path/to/wordpress/wp-config.php
tail -5 /path/to/wordpress/wp-config.phpRegenerate your security keys by obtaining new values from https://api.wordpress.org/secret-key/1.1/salt/ and replacing the old ones in wp-config.php.
Step 5: Check Cron Jobs
Hackers sometimes use WordPress cron tasks to reinject malicious code:
# List all cron tasks
wp cron event list
# Search for suspicious tasks
wp cron event list --fields=hook,next_run,recurrence | grep -v "wp_\|woocommerce_\|action_scheduler"Remove any cron task you do not recognize.
Post-Cleanup Verification
After cleanup, thorough verification is essential.
Verification Checklist
- Test navigation: visit the site in incognito mode, from Google, with different devices
- Scan again: run a full scan with Wordfence or Sucuri
- Check Google Search Console: review the "Security Issues" report
- Test redirects with
curl(see commands above) - Monitor logs for 48 hours:
# Monitor suspicious access in Apache logs
tail -f /var/log/apache2/access.log | grep -i "eval\|base64\|redirect"
# Monitor file modifications
find /path/to/wordpress/ -name "*.php" -newer /path/to/wordpress/wp-config.php -type fRequest a Google Review
If your site was flagged as dangerous by Google Safe Browsing, see our detailed guide on getting off the Google blacklist:
- Log in to Google Search Console
- Go to Security & Manual Actions > Security Issues
- Click Request a Review after cleaning the site
- Describe the cleanup actions taken
The review typically takes 24 to 72 hours.
Why the Redirect Hack Keeps Coming Back
The redirect hack is notoriously known for its tendency to return. Here is why:
| Reinfection Cause | Explanation |
|---|---|
| Unremoved backdoor | A hidden backdoor file allows the hacker to reinject code |
| Compromised admin accounts | An admin account created by the hacker remains active |
| Vulnerable plugin | The plugin that served as the entry point was not updated |
| Malicious cron job | A scheduled task reinjects code at regular intervals |
| Files in /uploads/ | Hidden PHP scripts in the uploads folder are overlooked |
Prevention: Stopping Redirect Hacks
The best defense is a multi-layered preventive approach.
Secure the .htaccess File
# Protect .htaccess from modifications
<Files .htaccess>
Order Allow,Deny
Deny from all
</Files>Set file permissions to 444 (read-only):
chmod 444 /path/to/wordpress/.htaccessHarden wp-config.php
Add these constants to limit editing capabilities:
// Disable file editor in dashboard
define('DISALLOW_FILE_EDIT', true);
// Force SSL for administration
define('FORCE_SSL_ADMIN', true);
// Limit post revisions
define('WP_POST_REVISIONS', 5);Set Up Monitoring
| Solution | Function | Frequency |
|---|---|---|
| Wordfence | File and malware scanning | Daily |
| Sucuri | WAF firewall + monitoring | Real-time |
| UptimeRobot | Redirect monitoring | Every 5 min |
| Google Search Console | Security alerts | Continuous |
Security Best Practices
- Update WordPress, themes, and plugins as soon as patches are available, or delegate this to a WordPress maintenance service
- Use strong passwords and two-factor authentication (2FA)
- Limit the number of administrator accounts to the strict minimum
- Remove inactive plugins and themes
- Choose a secure host with account isolation
- Perform regular backups and test their restoration
When to Call an Expert
If the redirect hack returns after multiple cleanup attempts, or if you are not comfortable with technical operations, it is wise to entrust the cleanup to a professional. A WordPress malware removal expert has the tools and experience to identify all layers of infection, including the most sophisticated backdoors.
Conclusion
The WordPress redirect hack is a serious infection that can destroy your reputation, your SEO rankings, and your visitors' trust. The key to successful cleanup is methodology: diagnose the redirect type, systematically clean each layer (files, database, cron jobs), verify the absence of backdoors, and implement solid preventive measures.
Do not wait for Google to flag your site as dangerous. If you notice signs of hacking or need a complete cleanup guide, act immediately. And stay informed about common WordPress malware in 2026 to better protect yourself.
