Written by 5:38 am Beginner’s Guide, Checklists Views: 0

How to Fix a WordPress Redirect Hack That Sends Visitors to Spam Sites (2026 Guide)

A WordPress redirect hack silently sends your visitors to casino, pharma, or spam sites without you knowing. This guide shows you exactly where redirect malware hides in WordPress — .htaccess, theme functions.php, wp_options, and fake image files — and how to find and remove every instance.

WordPress redirect hack removal guide showing 9-step process to find and clean redirect malware from .htaccess, database, and theme files

Visitors are landing on your WordPress site and immediately getting sent somewhere else. You cannot reproduce it yourself because the redirect targets new visitors or mobile users only. Meanwhile, your site is hemorrhaging traffic, your Google rankings are dropping, and you may not even know it is happening.

This is the WordPress redirect hack. It is one of the most common WordPress infections and one of the hardest to find because the attacker specifically hides the redirect from logged-in users and site owners. This guide covers every location where redirect malware hides and exactly how to remove it.


How the WordPress Redirect Hack Works

The redirect hack injects code that checks who is visiting and selectively redirects certain visitors. Common targeting patterns:

  • Only redirects users arriving from Google (not direct visits)
  • Only targets mobile users (desktop users see the real site)
  • Only affects users who are not logged into WordPress
  • Only triggers on the first visit (sets a cookie and skips repeat visitors)
  • Redirects to different spam domains based on the visitor’s country

This targeting is why you often cannot reproduce the redirect in your own browser. Open the site in a private window or use a mobile device not on your IP address to test.

To test for a Google-referral redirect: open a private browser window, search Google for your site’s name, then click the result. If you get redirected, the hack is confirmed.


Where Redirect Malware Hides in WordPress

LocationWhat to Look ForPriority
.htaccessRewriteRule redirecting to external domainsCheck first
wp_options tableObfuscated code in option values, rogue siteurl/homeCheck second
Theme functions.phpeval(), base64_decode(), ob_start() at top of fileHigh
wp-config.phpInjected code above or below the database configHigh
index.php filesModified root or wp-content index.phpMedium
Plugin filesObfuscated code appended to legitimate plugin filesMedium
Uploads directoryPHP files disguised as .jpg or .ico filesMedium
wp-includes/js/Injected JS files or modified jQueryCheck if others clean

Step 1: Check and Clean .htaccess

The .htaccess redirect is the most common and simplest form of this hack. Download your .htaccess file via FTP or your host’s file manager. The clean WordPress default looks like this:

# 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

If you see anything above the BEGIN WordPress comment or below the END WordPress comment that you did not add, it is malicious. Common patterns:

# Malicious examples to look for and remove:
RewriteCond %{HTTP_REFERER} .*google.*
RewriteRule ^(.*)$ https://spam-site.com/ [R=301,L]

# Or mobile-targeting:
RewriteCond %{HTTP_USER_AGENT} "(android|blackberry|iphone|ipod|mobile)" [NC]
RewriteRule ^(.*)$ https://spam-site.com/ [R=301,L]

Delete everything outside the WordPress block. Then regenerate the file: go to Settings > Permalinks > Save Changes to write a fresh clean .htaccess.

If you have WordPress in a subdirectory or use WooCommerce, your .htaccess may have additional legitimate rules. Compare against what you originally installed, not just the bare WordPress default. If in doubt, ask your hosting provider which rules they added during account setup before deleting.


Step 2: Scan the Database for Redirect Code

The redirect code is often stored in the database in obfuscated form. Check wp_options first:

-- Check for JavaScript injection in wp_options:
SELECT option_name, LEFT(option_value, 500)
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%'
OR option_value LIKE '%unescape(%'
OR option_value LIKE '%fromCharCode%';

The hack often uses JavaScript stored in a wp_options row that gets output into the page header. The obfuscated JavaScript then does the redirect client-side so it bypasses .htaccess scans.

Also check if the siteurl or home option was changed:

SELECT option_name, option_value
FROM wp_options
WHERE option_name IN ('siteurl', 'home', 'blogname');

If either siteurl or home points to a domain that is not yours, that is the redirect. Update them:

UPDATE wp_options
SET option_value = 'https://your-real-domain.com'
WHERE option_name = 'siteurl';

UPDATE wp_options
SET option_value = 'https://your-real-domain.com'
WHERE option_name = 'home';

Step 3: Check Theme Files for Injected Code

The most persistent redirect hacks live in theme files, especially functions.php. Download your active theme folder and look for:

# Search for common obfuscation patterns:
grep -r "eval(" wp-content/themes/your-theme/
grep -r "base64_decode" wp-content/themes/your-theme/
grep -r "ob_start" wp-content/themes/your-theme/
grep -r "document.location" wp-content/themes/your-theme/
grep -r "window.location" wp-content/themes/your-theme/

The injected code is often added at the very top or very bottom of functions.php, header.php, or footer.php. It frequently looks like a long string of random characters passed through eval() or base64_decode().

Example of what injected code looks like (this is malware, do not run it):

<?php eval(base64_decode('aWYgKGlzc2V0KCRfU0VSVkVSWydIVFRQX1JFRkVSRVInXSkpIHsgLi4uIH0=')); ?>

Remove the entire injected block. If you cannot tell where the malicious code ends and the legitimate theme code begins, delete the functions.php file and replace it with the original from the theme developer.


Step 4: Check wp-config.php and index.php

These two files are targeted because they load on every request. Open each one and look for code that should not be there:

wp-config.php

This file should contain only PHP constant definitions, the database connection, table prefix, and the require for wp-settings.php. Anything else at the top or bottom of the file is suspicious. A fresh download of wp-config-sample.php from WordPress.org shows the expected structure.

index.php (root)

The root index.php should contain only:

<?php
/**
 * Front to the WordPress application.
 */

/** Tells WordPress to load the WordPress theme and output it. */
define( 'WP_USE_THEMES', true );

/** Loads the WordPress Environment and Template */
require __DIR__ . '/wp-blog-header.php';

If yours has anything else before the <?php or after the require line, remove it.


Step 5: Scan for PHP Files in Uploads

Attackers hide PHP scripts in the uploads directory disguised as image files. These scripts can serve as a persistent backdoor or as the redirect engine itself:

# Find PHP files in uploads:
find wp-content/uploads/ -name "*.php" -type f

# Find files with PHP extension hidden in other extensions:
find wp-content/uploads/ -type f | xargs grep -l "<?php" 2>/dev/null

# Find .ico files (common camouflage for PHP backdoors):
find wp-content/uploads/ -name "*.ico" -type f

Any PHP file in wp-content/uploads is malicious. Delete every one you find. Then add this protection permanently by creating a .htaccess file inside wp-content/uploads/:

# wp-content/uploads/.htaccess
<Files "*.php">
  Require all denied
</Files>

Step 6: Reinstall WordPress Core and Plugins

After manually removing redirect code, reinstall core and all plugins from clean sources to make sure no infected files remain:

# Reinstall WordPress core files (skips wp-content):
wp core download --skip-content --force --allow-root

# Verify core file integrity:
wp core verify-checksums --allow-root

# Update all plugins to get clean versions:
wp plugin update --all --allow-root

If any plugin cannot be updated because it is abandoned or the author removed it from the repository, deactivate and delete it. An abandoned plugin with a known redirect vulnerability is a ticking clock.


Step 7: Reset Credentials and Regenerate Salts

After cleaning the files and database:

  1. Generate new WordPress security keys and salts at https://api.wordpress.org/secret-key/1.1/salt/ and replace the existing keys in wp-config.php. This invalidates all current sessions.
  2. Change all WordPress admin passwords
  3. Change the database password and update wp-config.php
  4. Change FTP credentials
  5. Remove any admin accounts you did not create

Step 8: Verify the Redirect Is Gone

After cleaning, test from multiple angles before removing maintenance mode:

  • Open a private browser window and visit the site directly
  • Set your browser user agent to Android mobile and visit (use developer tools > device toolbar in Chrome)
  • Search for your site on Google, click the result in an incognito window
  • Run the URL through Google Safe Browsing: https://transparencyreport.google.com/safe-browsing/search
  • Run Sucuri SiteCheck at sitecheck.sucuri.net to scan for known redirect malware patterns

If any test still shows a redirect, you missed a location. Go back through Steps 1 to 6 and check more carefully. Common missed spots: a second .htaccess file in wp-content/, or a mu-plugin file in wp-content/mu-plugins/ that you overlooked. Also check whether your host’s server-level config (nginx.conf or Apache virtual host) has redirect rules that sit above .htaccess.


Step 9: Request Google Review if Blacklisted

If Google Search Console shows a security issue or your site is flagged in search results:

  1. Go to Google Search Console > Security and Manual Actions > Security Issues
  2. Click Request a Review
  3. Explain specifically what you cleaned: which files, which database rows, what you changed to prevent recurrence
  4. Submit and wait 1 to 3 business days for Google to re-crawl and remove the warning

Prevent Redirect Hacks From Happening Again

Most redirect hacks enter through outdated plugins or nulled themes. Prevent recurrence:

Enable auto-updates for plugins

// wp-config.php:
add_filter( 'auto_update_plugin', '__return_true' );

Block PHP execution in uploads permanently

The .htaccess in uploads/ shown in Step 5 prevents PHP backdoors from running even if they are uploaded in the future. This one file blocks the most common re-infection vector. Create it now and verify it is in place after every migration or restore.

Install a file integrity monitor

Wordfence and iThemes Security both offer file change monitoring. When any core or theme file is modified, you get an email alert immediately instead of finding out weeks later from a visitor complaint. Configure alerts to go to an email address that does not use the same hosting account, so an attacker who compromises the server cannot suppress the notification.

Use a WAF (Web Application Firewall)

Cloudflare’s free plan includes basic WAF rules. Sucuri’s WAF blocks exploit attempts before they reach WordPress. Either stops the most common attack vectors that lead to redirect hacks.

For a complete security hardening checklist that goes beyond redirect hacks, see our 20-point WordPress security audit checklist with monthly checks for file permissions, login security, SSL, and HTTP headers.


Redirect Hack vs Other WordPress Hacks

The redirect hack is a specific attack type. If you are dealing with a different infection pattern, see our complete guide on how to fix a hacked WordPress site which covers all six hack types including SEO spam injection, admin backdoors, webshells, and phishing pages.


Frequently Asked Questions

Why do I get redirected but my developer does not?

The redirect code specifically targets certain visitor types. It usually skips logged-in WordPress users, visitors on the site’s own IP address, and repeat visitors (via cookie). Your developer is likely logged in. Test in a private window with a VPN or from a mobile device.

My redirect only happens on mobile. Where is it?

Mobile-only redirects are most commonly in .htaccess (checking the user agent string) or in JavaScript injected into a theme file (checking screen width or user agent via JS). Start with .htaccess (Step 1) and then scan theme files for window.location or document.location.

My .htaccess looks clean but the redirect still happens. What next?

A clean .htaccess means the redirect is JavaScript-based, not server-side. Check wp_options for injected JavaScript (Step 2), then theme functions.php and header.php (Step 3). JavaScript redirects look for window.location, document.location, or window.location.href assignments in the source code of a page.

How did the attacker get in?

The most common entry points for redirect hacks: a plugin with a known file upload or authentication bypass vulnerability, a nulled theme from a torrent or shady site, compromised FTP credentials from a keylogger or data breach, or shared hosting cross-contamination from another site on the same server.

The redirect keeps coming back after I clean it. Why?

A persistent redirect that returns after cleaning means the attacker left a backdoor that is re-injecting the code. Common backdoors: a PHP file in uploads/, a mu-plugin (in wp-content/mu-plugins/), or a database-stored cron job that writes the redirect code back. Run a full file scan with Wordfence and check the wp-cron and wp_options tables for scheduled re-infection tasks.


Clean Once, Harden Permanently

The redirect hack thrives on unpatched plugins and missing upload protections. Once you remove every instance using this guide, spend 30 minutes on the prevention steps: block PHP in uploads, enable file monitoring, and turn on auto-updates for plugins. That combination stops the overwhelming majority of redirect hacks before they can install.

Visited 1 times, 1 visit(s) today

Last modified: April 24, 2026

Close