Last updated: November 5, 2026 · Skill level: intermediate
If your WordPress site is redirecting to a spam site, an attacker has planted a conditional redirect in .htaccess, a PHP file, the database, or a script your pages load. It usually fires only for logged-out, mobile, or Google-referred visitors. Back up first, reproduce it with curl, find every injection point, clean every one, then ask Google for a review.
TL;DR: A Location header in a curl response means the redirect is server-side, so check .htaccess, wp-config.php, core files, PHP settings, and your CDN. A clean header plus a redirect in the browser means JavaScript, so check the database, theme, plugins, and third-party scripts. Clean every location before you request a Google review, or the warning comes back.
Why does my WordPress site redirect only some visitors?
Redirect malware is conditional on purpose, so the site owner never sees it. Typical checks are the referrer (Google, Facebook), the device (iPhone, Android), whether a WordPress login cookie exists, and a marker cookie that limits each visitor to one redirect. Sucuri has documented every one of these conditions in real infections.
Three published Sucuri cases show how the conditions stack up:
| Case | Where the code lived | Conditions checked before redirecting |
|---|---|---|
| Curious .htaccess conditional redirect (September 23, 2014) | .htaccess | Referrer is Google, Facebook, or Twitter; OS is Windows, Mac, iPhone, iPad, iPod, or Android; cookie cNL not set yet, so each visitor is redirected once |
| Mobile redirect to a porn app (July 9, 2014) | index.php, wp-config.php, theme functions.php | Mobile devices only; once per day per IP address; skips visitors with logged-in cookies |
| Malware redirects WordPress traffic to harmful sites (January 23, 2025) | Active theme functions.php | Skips logged-in users, search engine crawlers, and bots; skips /wp-login.php and /wp-json URLs; stops if cookie MkQQ is present |
The practical result: “it works fine for me” proves nothing. You are logged in, on a desktop, typing the URL directly, and you may already carry the marker cookie. That is exactly the visitor profile the malware is written to ignore.
Spam redirects also rarely travel alone. Sucuri’s 2023 Hacked Website and Malware Threat Report (published June 12, 2024) found SEO spam on 42.22% of infected websites, and at least one backdoor on 49.21% of compromised websites at the point of cleanup. Plan to find the backdoor, not just the redirect.
How do I reproduce the redirect safely?
Reproduce it from the command line, not your logged-in browser. curl shows the raw server response without running JavaScript or following redirects, so you see a 301 or 302 Location header, or an injected script tag, without landing on the scam page. Test plain, mobile, Google-referred, and Googlebot requests, then compare the results.
Replace example.com and /some-post/ with your own URLs. Test an inner post as well as the home page, because some infections skip the front page. These commands are read-only and change nothing on the server:
UA_MOBILE="Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
UA_BOT="Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
# 1. Plain desktop request: no cookies, no referrer, redirects not followed
curl -s -o /dev/null -D - https://example.com/some-post/ | grep -iE "^HTTP|^location"
# 2. Desktop visitor arriving from Google
curl -s -o /dev/null -D - -e "https://www.google.com/" https://example.com/some-post/ | grep -iE "^HTTP|^location"
# 3. Mobile visitor arriving from Google
curl -s -o /dev/null -D - -A "$UA_MOBILE" -e "https://www.google.com/" https://example.com/some-post/ | grep -iE "^HTTP|^location"
# 4. Googlebot user agent (cloaked SEO spam often serves crawlers different content)
curl -s -o /dev/null -D - -A "$UA_BOT" https://example.com/some-post/ | grep -iE "^HTTP|^location"
If every response is a 200 with no Location header, the redirect is probably JavaScript. Save the page as a normal visitor and as a mobile visitor from Google, then compare the two. Lines that appear only in the second file are your conditional injection. Ignore nonces and timestamps that change on every request.
curl -s https://example.com/some-post/ > plain.html
curl -s -A "$UA_MOBILE" -e "https://www.google.com/" https://example.com/some-post/ > mobile-google.html
diff plain.html mobile-google.html
# List external scripts and common redirect or obfuscation patterns in the suspicious version
grep -oiE "<script[^>]+src=[^ >]+|window\.location|location\.href|location\.replace|atob\(|fromCharCode" mobile-google.html | sort | uniq -c
Two Google tools fill the gaps curl leaves. The URL Inspection tool in Search Console runs a live test as Googlebot and shows the rendered HTML. Google’s Safe Browsing site status page shows whether Google currently flags the domain. If you need to see the redirect in a real browser, use a phone on mobile data in a private tab, tap your own result in Google, and never enter anything on the page you land on.
Write down which request triggered the redirect. It tells you which layer to search first:
| What you see | What it usually means | Start looking in |
|---|---|---|
Location header pointing to a domain you don’t own | Server-side redirect, before or inside WordPress | .htaccess, wp-config.php, index.php, PHP settings, theme and plugin PHP |
200 response, but the browser ends up elsewhere | JavaScript redirect | wp_posts, wp_postmeta, widget options, theme templates, plugin assets, third-party scripts |
| Everyone goes to the spam domain, including wp-admin | Site URL changed, or DNS/CDN hijack | siteurl and home options, WP_HOME/WP_SITEURL constants, DNS records, CDN rules |
| Only Googlebot gets different content | Cloaked SEO spam | Server-side locations, plus the URL Inspection rendered HTML |
What should I do before changing anything?
Take a full backup of the files and the database, keep one untouched copy as evidence, and do your analysis on a staging copy if your host offers one. Cleanup commands overwrite files and database rows. Without a backup, one wrong delete can take the site down. Without evidence, you can’t work out how the attacker got in.
# Database dump: reads the database, writes one .sql file in your home directory (outside the web root)
wp db export ~/incident-$(date +%F)-db.sql
# File archive: reads the site directory, writes one .tar.gz in your home directory
tar -czf ~/incident-$(date +%F)-files.tar.gz -C /var/www example.com
Adjust /var/www and example.com to your server’s layout, download both files, and delete them from the server afterward. Also download your web server access logs now; many hosts rotate them within days, and they are the only record of the request that planted the redirect.
While you investigate, add --skip-plugins --skip-themes to every WP-CLI command that loads WordPress. That stops malicious plugin or theme code from running in your terminal session, or from filtering itself out of the results.
Where do WordPress redirect hacks hide?
Redirect code hides in nine common places: .htaccess files, wp-config.php, core files such as index.php, the siteurl and home options, post content, theme files, must-use plugins, fake plugins, and server or CDN settings. Check all nine. Infections often sit in several places at once; Sucuri’s 2014 mobile case planted the same code in four files.
| Location | What it looks like | How to check |
|---|---|---|
.htaccess (root and subfolders) | RewriteCond lines testing HTTP_REFERER or HTTP_USER_AGENT, followed by a RewriteRule to a foreign domain, often above # BEGIN WordPress | grep -rniE --include=".htaccess" "HTTP_REFERER|HTTP_USER_AGENT" . |
wp-config.php | An extra include or require of an odd file, or an eval/base64_decode blob at the top or bottom | grep -nE "eval\(|base64_decode|include|require" wp-config.php |
index.php and other core files | A root index.php longer than its usual short loader; modified files in wp-includes or wp-admin | wp core verify-checksums --include-root |
siteurl and home in wp_options | Either value set to a domain you don’t own; even wp-admin redirects | wp option get siteurl and wp option get home |
Post content in wp_posts | A <script> tag using atob(, fromCharCode, or an unknown external src, appended to posts | wp db search "<script" wp_posts --one_line |
Theme functions.php and header.php | A hook on init, template_redirect, or wp_head that calls wp_redirect() or header(), or prints obfuscated script | grep -rnE "eval\(|base64_decode\(|atob\(" wp-content/themes/ |
| Must-use plugins | A file in wp-content/mu-plugins/ you didn’t add; not shown in the main Plugins list | ls -la wp-content/mu-plugins/ |
| Fake plugins | A generic name, no readme, unknown to WordPress.org, sometimes hidden from the admin list | wp plugin list --fields=name,status,version,wporg_status |
| Server and CDN | auto_prepend_file in .user.ini, a hosting-panel redirect, a CDN rule, or changed DNS | grep -rn --include=".user.ini" "auto_prepend_file" . and curl --resolve |
How do I check .htaccess for redirect rules?
Apache and LiteSpeed apply an .htaccess file to its own directory and everything below it, so an injected rule in the web root runs before WordPress loads. Look for referrer or user-agent conditions and for rewrites that point to external URLs.
# Read-only: list every .htaccess file with its size and modification time
find . -name ".htaccess" -type f -exec ls -la {} \;
# Read-only: show referrer/user-agent conditions and external rewrites, with line numbers
grep -rniE --include=".htaccess" "HTTP_REFERER|HTTP_USER_AGENT|RewriteRule.*https?://" .
A basic single-site install needs only the block documented in the WordPress Apache guide (last modified October 14, 2026). WordPress may wrap it in an <IfModule mod_rewrite.c> container:
# BEGIN WordPress
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
Caching, security, and HTTPS plugins add their own legitimate blocks, usually between labeled # BEGIN and # END comments, and some of them test the user agent. A rule that sends search-engine referrers or phone user agents to a domain you don’t recognize is not one of them. Edit the affected .htaccess file and delete the injected lines. Re-saving Settings > Permalinks only rewrites the lines between the WordPress markers, so injected rules outside them stay until you remove them by hand.
How do I check wp-config.php and index.php?
WP-CLI compares core files against WordPress.org checksums, which catches an edited root index.php, wp-blog-header.php, or anything under wp-includes and wp-admin. It can’t check wp-config.php, because that file is unique to your site, so read it yourself.
# Read-only: compare core files with WordPress.org checksums and flag unknown files in the root
wp core verify-checksums --include-root
# Read-only: the root index.php should be a short loader that requires wp-blog-header.php
cat index.php
# Read-only: obfuscation functions, file includes, and URL overrides in wp-config.php
grep -nE "eval\(|base64_decode|gzinflate|str_rot13|include|require|WP_HOME|WP_SITEURL" wp-config.php
In a normal wp-config.php, the only require is require_once ABSPATH . 'wp-settings.php'; near the end. Treat any line that loads a file from wp-content/uploads, /tmp, or a random path as malicious until proven otherwise. Our guide to verifying WordPress core files with WP-CLI explains how to read every type of checksum warning.
How do I check siteurl and home in wp_options?
If siteurl or home points to a foreign domain, every visitor goes there, including you on wp-admin. Check both values, and check wp-config.php for WP_HOME or WP_SITEURL constants, which override the database.
# Read-only
wp option get siteurl --skip-plugins --skip-themes
wp option get home --skip-plugins --skip-themes
# Fix (writes one row each in wp_options)
wp option update siteurl 'https://example.com' --skip-plugins --skip-themes
wp option update home 'https://example.com' --skip-plugins --skip-themes
The wp_options table has more hiding spots than these two rows, including widget content and autoloaded options. Rather than repeat them here, walk through our guide on checking wp_options for malicious entries.
How do I find injected JavaScript in wp_posts?
Injected JavaScript is often appended to many posts at once, and page builders store layout data in wp_postmeta, so search both tables. Run wp db prefix first and replace wp_ below if your prefix differs. These searches are read-only and case-insensitive by default.
wp db prefix
# Script tags in post content and post meta, one match per line
wp db search "<script" wp_posts wp_postmeta --one_line --skip-plugins --skip-themes
# Common obfuscation functions (regex mode)
wp db search "atob\(|fromCharCode|eval\(" wp_posts wp_postmeta --regex --one_line --skip-plugins --skip-themes
# Which posts are affected, most recently modified first
wp db query "SELECT ID, post_type, post_status, post_modified FROM wp_posts WHERE post_content LIKE '%<script%' ORDER BY post_modified DESC;"
Forms, maps, and ad code also use script tags, so judge each match. Once you have the exact injected string, remove it with a dry run first, then run the same command without --dry-run, which writes to wp_posts:
wp search-replace '<script src="https://bad.example/x.js"></script>' '' wp_posts --dry-run --skip-plugins --skip-themes
How do I check theme functions.php and header.php?
Theme files run on every page load, which makes functions.php and header.php favorite spots for PHP redirects and injected script output. Search the themes directory for obfuscation and redirect calls, then list PHP files whose inode changed recently.
# Read-only: obfuscation and visitor-fingerprinting patterns
grep -rnE "eval\(|base64_decode\(|gzinflate\(|str_rot13\(|atob\(|fromCharCode|document\.referrer|navigator\.userAgent" wp-content/themes/
# Read-only: server-side redirects
grep -rnE "wp_redirect\(|header\([[:space:]]*.Location" wp-content/themes/
# Read-only: PHP files under wp-content whose inode changed in the last 14 days
find wp-content -type f -name "*.php" -ctime -14 -ls
-ctime uses the inode change time, which touch cannot backdate, unlike the modification time attackers often fake. wp_redirect() and document.referrer appear in legitimate themes too. What matters is a redirect to a domain you don’t own, or code you can’t read. Reinstall a WordPress.org theme with wp theme install <slug> --force, which overwrites that theme’s folder. Replace a commercial or custom theme from the vendor’s download or your Git repository, and review a child theme by hand.
How do I check must-use plugins and drop-ins?
Must-use plugins load automatically before normal plugins, can’t be disabled from wp-admin, and appear only in a separate Must-Use list, according to the WordPress must-use plugins documentation (last modified October 14, 2026). That makes wp-content/mu-plugins/ an ideal hiding place.
# Read-only
ls -la wp-content/mu-plugins/
wp plugin list --status=must-use --skip-plugins --skip-themes
wp plugin list --status=dropin --skip-plugins --skip-themes
Managed hosts and some plugins add legitimate must-use files. For any file you can’t attribute to your host or a plugin you installed, move it out of the web root instead of deleting it, so you keep the evidence: mv wp-content/mu-plugins/suspicious.php ~/evidence/. Give drop-ins such as advanced-cache.php, object-cache.php, and db.php the same scrutiny.
How do I spot a fake plugin?
Attackers install plugins with plausible names that exist nowhere else, and some hide themselves from the Plugins screen. Compare the folder listing with WP-CLI’s list, check which plugins WordPress.org knows, and verify checksums for the plugins it hosts.
# Read-only
ls -la wp-content/plugins/
wp plugin list --fields=name,status,version,wporg_status --skip-plugins --skip-themes
wp plugin verify-checksums --all --skip-plugins --skip-themes
verify-checksums only works for plugins that WordPress.org publishes checksums for, so premium plugins won’t verify; replace those from the vendor’s download. A folder with no vendor, no readme, and a recent change time is the strongest signal. Anyone who could install a plugin had administrator-level access, so also follow our guide to finding and removing rogue WordPress admin accounts.
What if the redirect comes from the server or CDN?
If WordPress is clean but visitors still bounce, the redirect sits outside it: a PHP auto_prepend_file setting that runs a file before every script, the web server configuration, a redirect set in your hosting panel, a CDN redirect rule or worker, changed DNS records, or a compromised third-party script your theme loads.
# Read-only: PHP files injected through per-directory PHP settings
grep -rnE --include=".user.ini" --include="php.ini" "auto_(prepend|append)_file" .
# Read-only: where the domain points now
dig +short example.com A
# Read-only: request the origin server directly, bypassing the CDN (use your real origin IP)
curl -s -o /dev/null -D - --resolve example.com:443:203.0.113.10 https://example.com/
If the origin answers cleanly but the public domain redirects, check your CDN dashboard for redirect rules and workers, check your registrar’s DNS records, and change both account passwords. Nginx server blocks live outside your web root, so ask your host to review them. For third-party scripts, take every external src from the earlier curl output and confirm each domain belongs to a service you actually use.
How do I fix a WordPress redirect hack step by step?
Work in a fixed order: lock down access, preserve evidence, replace every file you can from a clean source, hand-clean the files you can’t replace, clean the database, remove unknown code and users, rotate every secret, close the entry point, purge caches, then retest with the same requests that reproduced the redirect.
- Lock down access. From a clean device, change your hosting panel, SFTP or SSH, and database passwords. If you change the database password, update DB_PASSWORD in wp-config.php at the same time or the site goes offline.
- Back up and preserve evidence. Run the database export and file archive commands, download them along with the access logs, and keep one copy untouched.
- Replace WordPress core. Overwrite core files with a fresh copy of the same version using wp core download –skip-content –force, then confirm with wp core verify-checksums –include-root and review any unknown root files it reports.
- Reinstall plugins from source. Reinstall each WordPress.org plugin with wp plugin install –force, replace premium plugins from the vendor download, delete plugins you do not use, then run wp plugin verify-checksums –all.
- Replace the theme. Reinstall the parent theme from WordPress.org, the vendor, or your Git repository, and review the child theme line by line.
- Clean the files you cannot replace. Remove injected lines from every .htaccess file, wp-config.php, and any .user.ini or php.ini that sets auto_prepend_file.
- Clean the database. Fix siteurl and home if they changed, remove injected scripts from wp_posts and wp_postmeta with a dry-run search-replace first, and review wp_options for other malicious entries.
- Remove unknown code. Move unknown must-use plugins, drop-ins, fake plugins, and any PHP files in wp-content/uploads to an evidence folder outside the web root.
- Remove rogue users and rotate secrets. Delete administrator accounts you do not recognize, shuffle the salts in wp-config.php, and reset every administrator password.
- Close the entry point. Match the earliest changed file times against POST requests in the access logs, then update or remove the plugin, theme, or account the attacker used.
- Purge every cache. Flush the object cache, the page cache plugin, the host cache, and the CDN so no cached page keeps serving the injected script.
- Retest the way you reproduced it. Rerun the four curl requests and the HTML diff, then tap your site in Google results from a phone on mobile data. Every request should return your own page.
The commands for the replace, rotate, and purge steps:
# Step 3: overwrite core files with a clean copy of the same version
# (touches wp-admin, wp-includes, and root PHP files; leaves wp-content and wp-config.php alone)
wp core download --skip-content --force --version=$(wp core version)
wp core verify-checksums --include-root
# Step 4: reinstall a WordPress.org plugin over itself (overwrites wp-content/plugins/<slug>)
wp plugin install <slug> --version=<installed-version> --force
wp plugin verify-checksums --all
# Step 8: the uploads folder should normally contain no PHP files
find wp-content/uploads -type f -name "*.php"
# Step 9: rewrite the salt lines in wp-config.php (logs every user out), then reset admin passwords
wp config shuffle-salts
wp user reset-password $(wp user list --role=administrator --format=ids)
# Step 11: flush the object cache (purge page caches and the CDN in their own dashboards)
wp cache flush
How do I get Google to remove the hacked site warning?
Once every page is clean, open the Security Issues report in Google Search Console, confirm each listed issue is fixed across the whole site, and select Request Review with a description of what you removed and which hole you closed. Google says hacked-with-spam reviews can take several weeks, malware reviews a few days, and phishing reviews about a day.
The flow, per Google’s Security Issues report help page and the web.dev guide to requesting a review (both accessed November 5, 2026):
- Confirm the fix with the curl tests above, and make sure
robots.txtrules ornoindextags don’t block Googlebot from the affected pages. - In Search Console, open Security & Manual Actions > Security issues. If you haven’t verified the property yet, do that first.
- Expand each issue, open the sample URLs, and confirm the problem is gone everywhere. Google says fixing only some pages does not return those pages to search results.
- Select Request Review and explain the exact issue, the steps you took to fix it, and the outcome. For example: removed redirect rules from
.htaccessand an injected script from every affected post, updated the vulnerable plugin, and rotated all passwords. - Wait for the confirmation email and the result email. Don’t resubmit while a request is pending; Google warns that this can slow your next review or get the site marked as a repeat offender.
How do I stop the redirect from coming back?
Close the door the attacker used and make the next change visible fast. That means updating everything, removing what you don’t use, disabling in-dashboard file editing, protecting every account with strong unique passwords and two-factor authentication, and running scheduled integrity checks so a new redirect shows up in hours, not weeks.
- Update core, plugins, and themes promptly. Sucuri’s 2023 report found 39.1% of CMS applications were outdated at the point of infection.
- Delete inactive plugins and themes. Deactivated code can still be reached and exploited if it is vulnerable.
- Add
define( 'DISALLOW_FILE_EDIT', true );towp-config.phpto turn off the built-in theme and plugin editors. - Use separate strong passwords for hosting, SFTP, the database, your CDN, and your domain registrar, with two-factor authentication wherever it is offered.
- Block PHP execution in
wp-content/uploadsso an uploaded backdoor can’t run. - Schedule
wp core verify-checksumsandwp plugin verify-checksums --allwith cron, and rerun the four curl requests weekly. - Add a scanner and firewall as a second line of defense; our comparison of the best WordPress malware removal plugins covers which ones catch file and database injections.
- Keep versioned offsite backups, so you can restore a known clean copy and diff against it next time.
Frequently asked questions
Why is my WordPress site redirecting to spam only on mobile?
The malware checks the User-Agent header for strings such as iPhone or Android and only redirects those requests, so desktop visitors and the site owner see a normal page. Reproduce it with curl using a mobile user agent and a Google referrer, then search .htaccess and theme PHP files for user-agent checks.
Why don’t I see the redirect when I’m logged in?
Many redirect scripts skip visitors who carry a WordPress login cookie, so administrators never trigger them. Sucuri documented this in a January 2025 functions.php infection. Log out, use a private window or curl without cookies, and arrive from a Google search result to see what visitors see.
Can a security plugin remove a WordPress redirect hack?
A scanner can find many injected files and database entries, but it cannot fix the vulnerability that let the attacker in, and it can miss server-level, DNS, or CDN redirects. Use a scanner as a second opinion after the manual checks in this guide, not as a replacement for them.
Will restoring a backup fix the redirect?
Only if the backup predates the infection and you also close the hole the attacker used. Restoring an old copy without updating the vulnerable plugin or changing the stolen passwords leaves the same door open. Check the backup with the same grep and checksum commands before you restore it.
How long does Google take to review a hacked site?
According to Google’s web.dev guidance, reviews for sites hacked with spam can take up to several weeks, malware reviews take a few days, and phishing reviews take about a day. You get an email when the request is received and another when the review is complete.
Can the redirect come from DNS or a CDN instead of WordPress?
Yes. A changed DNS record, a CDN redirect rule, or a CDN worker can redirect visitors before the request reaches WordPress. If the origin server returns a clean page when you bypass the CDN with curl –resolve, the problem is upstream, so check your registrar and CDN dashboards and change those passwords.
Sources:
- Sucuri, 2023 Hacked Website and Malware Threat Report, June 12, 2024: SEO spam, backdoor, and outdated-CMS figures.
- Sucuri, Curious .htaccess conditional redirect case, September 23, 2014: referrer, OS, and cookie conditions in
.htaccess. - Sucuri, Mobile redirect to porn app, July 9, 2014: mobile-only, once-per-IP, logged-in checks across four files.
- Sucuri, Malware redirects WordPress traffic to harmful sites, January 23, 2025:
functions.phpredirect with cookie, login, and bot checks. - Google, Security Issues report and web.dev, Request a review, accessed November 5, 2026.
- WordPress Developer Resources: wp core verify-checksums, wp plugin verify-checksums, wp db search, wp config shuffle-salts, wp user reset-password.


Leave a Reply