Skip to content
Mastodon

Blog

WordPress Redirects to Spam Sites on Mobile Only? Complete Mobile Redirect Malware Guide

24 min read
WordPress Redirects to Spam Sites on Mobile Only? Complete Mobile Redirect Malware Guide

Your WordPress website works normally on a laptop.

You open the homepage, visit a few pages, check the WordPress dashboard, and find nothing unusual.

But customers using phones are redirected to gambling pages, fake security warnings, adult advertisements, malicious applications, questionable subscriptions, or unrelated spam websites.

This is usually not a browser problem.

It is often a mobile-only WordPress redirect infection—a conditional malware campaign designed to attack selected visitors while remaining invisible to the website owner.

During one of my own WordPress malware investigations, desktop requests returned a normal 200 OK response while requests using a mobile user agent returned a 302 redirect. The malicious behavior was eventually traced to injected rules inside the root .htaccess file, while hidden shells elsewhere in the hosting account provided the attacker with persistent access.

That case demonstrates why mobile redirect malware is so difficult to investigate: removing the visible redirect is not the same as removing the compromise.

This guide explains:

  • How mobile-only redirect malware works
  • Why the infection may appear only once
  • Every common location where the malware can hide
  • Historical WordPress mobile malware samples
  • How to reproduce and confirm the redirect safely
  • How to inspect the files, database, logs and external scripts
  • How to remove the infection without leaving a backdoor behind
  • How to prevent the malware from returning

Quick answer: When WordPress redirects to a spam website only on mobile, malicious code is probably checking the visitor’s user agent, screen size, cookies, referrer, IP address or interaction before executing. The malware may be stored in .htaccess, wp-config.php, theme files, plugins, JavaScript, the WordPress database, an external script or a hidden backdoor. Cleaning only the redirect usually results in reinfection.


What Is WordPress Mobile Redirect Malware?

Mobile redirect malware is malicious code that sends selected website visitors to an external destination.

Unlike a normal site-wide redirect, it does not necessarily affect every visitor. The malware first checks whether the visitor meets specific conditions.

Those conditions may include:

  • The visitor is using Android or iOS
  • The browser identifies itself as mobile
  • The screen is below a particular width
  • The visitor arrived from Google
  • The visitor is not logged into WordPress
  • The IP address has not been redirected recently
  • A tracking cookie is absent
  • The visitor clicks or taps somewhere
  • The request is not from a known crawler or scanner
  • A random execution condition is met

The redirect executes only when enough conditions match.

Wordfence notes that website owners may be unable to reproduce a redirect even when mobile visitors continue experiencing it. Redirect code can exist in either site files or the database and may execute before the legitimate page finishes loading.

This selective behavior is why the infection is also called a conditional redirect.

A simple example of how the redirect behaves

Visit 1: Desktop browser
Mobile condition: No
Result: WordPress returns 200 OK

Visit 2: Android phone from Google
Mobile condition: Yes
Search referrer: Yes
Tracking cookie: No
Result: The infection attempts a 302 redirect

Visit 3: Same Android phone
Tracking cookie: Yes
Result: WordPress returns the normal page

Visit 4: Incognito mode or cleared cookies
Tracking cookie: No
Result: The redirect may appear again

This selective sequence is why the owner, scanner and customer can all receive different results from the same URL.


Why Does the Redirect Affect Mobile Visitors Only?

Attackers do not target phones by accident.

Mobile-only execution gives the malware several advantages.

The website owner is less likely to see it

Many website owners manage WordPress from a desktop computer. They check the homepage from the same browser, network and logged-in session every day.

The malware may deliberately exclude:

  • Desktop browsers
  • Logged-in administrators
  • Returning IP addresses
  • Visitors with a particular cookie
  • Security scanners
  • Search engine crawlers

The owner sees a clean website while real mobile visitors are redirected.

Mobile traffic can be monetized differently

Mobile visitors can be sent to:

  • Aggressive advertisements
  • Fake antivirus warnings
  • Subscription traps
  • Application download pages
  • Push-notification scams
  • Affiliate landing pages
  • Adult advertising
  • Fake CAPTCHA pages
  • Malicious Android downloads

Wordfence documented malvertising campaigns that redirected compromised-site visitors to destinations including tech-support scams, pharmaceutical advertising and malicious Android applications.

Mobile-only behavior avoids basic scanners

A scanner that requests the website using a desktop user agent may receive the legitimate page.

Some campaigns add several defensive layers: JavaScript must execute, a mobile user agent must be present, the visitor must interact with the page, and the remote redirect server may perform another server-side device check. Sucuri documented this multi-layer behavior in a 2023 campaign detected across thousands of compromised websites.

That is much harder to identify than a redirect that affects every request.


Common Symptoms of a WordPress Mobile Redirect Hack

A website may have mobile redirect malware when:

  • The site redirects on a phone but works on a computer
  • The redirect happens only when arriving from Google
  • The first visit redirects, but later visits work normally
  • Incognito mode makes the redirect return
  • Clearing cookies causes the redirect to happen again
  • Only particular pages are affected
  • Tapping anywhere opens a spam page
  • Android users are affected but iPhone users are not, or the reverse
  • The redirect appears only on mobile data or only on Wi-Fi
  • The destination changes between visits
  • Security scanners alternate between infected and clean results
  • The WordPress dashboard looks normal
  • The redirect returns after .htaccess is cleaned
  • New JavaScript files repeatedly appear
  • Unknown PHP files, administrator accounts or cron jobs return after deletion

A single redirect does not automatically prove that WordPress is infected. Browser extensions, malicious advertisements, DNS manipulation and compromised third-party scripts can cause similar symptoms.

However, repeated redirects affecting different mobile visitors are a strong reason to investigate the website and hosting environment.


Why the Redirect May Happen Only Once

A common mistake is testing the website once, seeing the redirect, refreshing the page and concluding that the problem has disappeared.

Many mobile redirect campaigns deliberately prevent immediate repetition.

Cookie-based filtering

The script sets a cookie after redirecting the visitor. Future requests detect the cookie and serve the legitimate page.

The _mauthtoken malware campaign used a cookie to control repeated execution while checking mobile user-agent strings. Sucuri continued finding variations of the infection years after its original appearance.

IP-based filtering

The attacker records the visitor’s IP address and prevents another redirect for several hours or an entire day.

A documented BaDoink campaign redirected mobile visitors only once per day per IP address and attempted to avoid logged-in site administrators.

Referrer-based filtering

The redirect may execute only when the visitor arrives from:

  • Google
  • Bing
  • Facebook
  • An advertisement
  • A particular external website

Opening the URL directly may show a clean page.

Interaction-based execution

Some scripts wait for the visitor to tap a menu, button, link or any part of the page.

The 2023 bogus URL-shortener campaign attached malicious behavior to a document click event, meaning the redirect did not occur until the visitor interacted with the page.

Random execution

The malware may redirect only a percentage of eligible visitors.

This reduces complaints and makes the infection harder to reproduce.


How Mobile Redirect Malware Detects a Phone

There is no single detection method used by every campaign.

About the code samples: The following examples are safe, defanged reconstructions based on behavior documented in real mobile redirect infections. Live domains and redirect operations have been disabled so the samples explain the malware without sending visitors anywhere.

1. Server-side user-agent detection

PHP or Apache examines the request’s User-Agent header before returning the page.

Conceptually, the malicious logic looks like this:

IF visitor user agent contains Android, iPhone or Mobile
AND visitor does not match an exclusion
THEN return an external redirect

Because this happens on the server, the browser may receive a 301, 302, 307 or another redirect response before WordPress renders the page.

Safe PHP reconstruction

<?php

$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

$is_mobile = preg_match(
    '/Android|iPhone|iPad|iPod|IEMobile|Opera Mini|BlackBerry|Mobile/i',
    $user_agent
);

$is_bot = preg_match(
    '/Googlebot|Bingbot|DuckDuckBot|YandexBot/i',
    $user_agent
);

$already_seen = isset($_COOKIE['_mauthtoken']);

if ($is_mobile && !$is_bot && !$already_seen) {
    $target = 'hxxps://spam-domain[.]example/landing';
    $intended_status = 302;

    // The real redirect operation has been removed.
}

This reconstruction shows three common evasion checks: the visitor must appear to be using a phone, must not look like a known search crawler, and must not already have the tracking cookie. In a live infection, the removed final stage could return a 302 response before WordPress displays the page.

2. Client-side JavaScript detection

The legitimate page begins loading, but injected JavaScript examines values such as:

navigator.userAgent
navigator.vendor
window.opera

The script redirects after deciding that the visitor is using a phone.

Safe JavaScript reconstruction

(function () {
    const userAgent = navigator.userAgent || "";

    const isMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(
        userAgent
    );

    const alreadySeen = document.cookie.includes(
        "_mauthtoken=1"
    );

    if (isMobile && !alreadySeen) {
        console.warn(
            "Mobile condition matched. Redirect disabled in this sample."
        );

        // Disabled malicious behavior:
        // window.location.replace(
        //     "hxxps://spam-domain[.]example/landing"
        // );
    }
})();

Code like this is often injected before the closing </head> tag in a theme’s header.php, inside a JavaScript bundle, or through database-controlled header and footer settings.

3. Screen-width detection

Some infections use a simple screen-size condition rather than a detailed user-agent list.

Sucuri documented a redirect that executed when the screen width was 480 pixels or less.

This method is imperfect. A small browser window or unusual device can match, while a modern phone reporting a wider logical viewport may not.

Safe screen-width reconstruction

const smallScreen = window.screen.width <= 480;

if (smallScreen) {
    console.log(
        "Small-screen condition matched. Redirect disabled."
    );

    // Disabled:
    // location.href =
    //     "hxxps://spam-domain[.]example/offer";
}

4. Remote traffic-distribution systems

The injected code may contain no final spam domain.

Instead, it contacts a remote server that decides:

  • Whether to redirect
  • Which country is eligible
  • Which campaign should receive the visitor
  • Whether the visitor appears automated
  • Which final landing page pays the best rate

This is why searching only for the destination domain can fail. The WordPress infection may contain only a loader or short intermediary URL.

How the redirect chain may work

Mobile visitor opens the WordPress page
                ↓
Injected code checks the device, cookie and referrer
                ↓
The loader contacts an intermediary server
                ↓
The remote server checks country, browser and campaign rules
                ↓
The visitor is assigned a spam or advertising destination

The final landing page can therefore change even when the compromised WordPress code remains exactly the same.


Where Mobile Redirect Malware Hides in WordPress

There is no universal malware location.

A complete investigation must cover the server configuration, WordPress files, database, scheduled tasks, users and external resources.

1. The Root .htaccess File

.htaccess is one of the most important locations to inspect when:

  • Mobile requests receive an immediate redirect
  • The redirect occurs before the page loads
  • WordPress PHP files appear clean
  • Desktop and mobile requests return different HTTP statuses

Suspicious indicators include:

HTTP_USER_AGENT
Android
iPhone
iPad
Mobile
RewriteCond
RewriteRule
An unfamiliar external domain

The malicious lines may appear:

  • Above the normal WordPress block
  • Below it
  • Between legitimate WordPress rules
  • After hundreds of blank spaces
  • On an extremely long line
  • Inside an .htaccess file in a subdirectory
  • In a parent directory above public_html

In my own mobile redirect case, comparing server logs showed a normal desktop response and a mobile 302. The redirect was then traced to mobile user-agent conditions inside .htaccess.

Example of a conditional .htaccess injection

# Safe reconstruction — all directives are disabled

# RewriteEngine On
# RewriteCond %{HTTP_USER_AGENT} "Android|iPhone|iPad|iPod|Mobile" [NC]
# RewriteCond %{HTTP_COOKIE} !mobile_redirect_seen=1 [NC]
# RewriteRule ^(.*)$ hxxps://spam-domain[.]example/landing [R=302,L]

# BEGIN WordPress
# RewriteBase /
# RewriteRule ^index\.php$ - [L]
# RewriteCond %{REQUEST_FILENAME} !-f
# RewriteCond %{REQUEST_FILENAME} !-d
# RewriteRule . /index.php [L]
# END WordPress

In this pattern, a mobile browser without the tracking cookie would be selected before the normal WordPress rewrite block runs. On an infected site, the attacker may place these lines above the WordPress rules so the external redirect happens before WordPress processes the request.

Htaccess based mobile only malware


2. wp-config.php

Attackers often choose wp-config.php because:

  • It loads during almost every WordPress request
  • Site owners rarely inspect its bottom section
  • It contains legitimate sensitive-looking code
  • A loader can execute before the theme is rendered

Check both the beginning and end of the file.

Look for:

  • Code after the normal stopping comment
  • Remote requests
  • Encoded strings
  • Unexpected file writes
  • Device checks
  • Dynamically generated JavaScript
  • Includes from unfamiliar paths

A 2023 mobile-focused campaign injected loader code at the bottom of wp-config.php, generated fake core-looking JavaScript files and served those files to mobile browsers.

Example of suspicious code appended to wp-config.php

/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';

$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

$mobile = preg_match(
    '/Android|iPhone|iPad|iPod|IEMobile|Opera Mini|Mobile/i',
    $ua
);

$bot = preg_match(
    '/Googlebot|Bingbot|DuckDuckBot|YandexBot/i',
    $ua
);

$seen = isset($_COOKIE['_mauthtoken']);

if ($mobile && !$bot && !$seen) {
    $destination = 'hxxps://redirect-domain[.]example/r.php';
    $status = 302;

    // Redirect operation intentionally removed.
}

The suspicious detail is not only the device check. It is also the location: unknown application logic appears after the normal WordPress loader. A real sample may be compressed, encoded, split across variables or used to generate another JavaScript file.

wp-config.php based mobile only redirect malware


3. Active and Inactive Theme Files

Commonly infected theme files include:

header.php
footer.php
functions.php
index.php
404.php
single.php
page.php
style.css

Do not inspect only the active theme.

Attackers may place a backdoor in:

  • An inactive theme
  • A renamed theme directory
  • A child theme
  • A fake theme
  • A file with a legitimate theme filename
  • A nested directory that the real theme does not normally contain

Historical mobile redirect campaigns have been found in theme functions.php and header.php files. BaDoink-related infections affected WordPress and other CMS websites while using device, IP and session conditions to hide the redirect.

Example found in a theme’s functions.php

$ua  = $_SERVER['HTTP_USER_AGENT'] ?? '';
$ref = $_SERVER['HTTP_REFERER'] ?? '';

$mobile = preg_match(
    '/Android|iPhone|iPad|iPod|Mobile/i',
    $ua
);

$search_visitor = preg_match(
    '/google\.|bing\.|yahoo\./i',
    $ref
);

$already_seen = isset($_COOKIE['_mauthtoken']);

if ($mobile && $search_visitor && !$already_seen) {
    $target = 'hxxps://redirect-domain[.]example/landing';

    // Redirect operation removed.
}

This pattern would target mobile visitors arriving from a search engine while ignoring direct visits. It helps explain why an administrator may fail to reproduce the redirect by typing the URL directly.

functions.php based mobile only redirect malware

Example found in a theme’s header.php

<?php wp_head(); ?>

<script>
(function () {
    const mobile = /Android|iPhone|iPad|iPod|Mobile/i.test(
        navigator.userAgent || ""
    );

    if (mobile) {
        console.log(
            "Mobile visitor detected. Redirect disabled."
        );

        // window.location.replace(
        //     "hxxps://spam-domain[.]example/landing"
        // );
    }
})();
</script>

</head>

When injected before </head>, the JavaScript can execute before the visible page finishes loading.

header.php based mobile only redirect malware


4. Plugins and Must-Use Plugins

Review:

/wp-content/plugins/
/wp-content/mu-plugins/

Pay special attention to:

  • Recently modified plugin files
  • Plugins not visible in the normal dashboard
  • Randomly named folders
  • Fake security or cache plugins
  • One-file plugins with vague headers
  • Plugins whose folder contents do not match an official copy
  • PHP files inserted into asset directories
  • Old vulnerable plugins that remain installed but inactive

Must-use plugins are especially important because they load automatically and are displayed separately from normal plugins.

Replacing only the active theme will not solve an infection controlled by a hidden plugin or must-use plugin.


5. WordPress Core Directories

Attackers frequently use filenames that look related to WordPress.

Inspect:

/wp-admin/
/wp-includes/

Compare core files with a clean copy of the same WordPress version.

The 2023 mobile-only campaign created files with names including:

style.wp.includes.js
jquery.wp.includes.js
style.public.html.js

The names were designed to resemble legitimate WordPress resources, but they were not standard core files.

Do not assume that a file is legitimate because its name contains wp, jquery, class, include or style.


6. JavaScript Files

Mobile redirect malware is often injected into:

  • Theme JavaScript
  • Plugin JavaScript
  • Minified bundles
  • Cache-generated files
  • Optimization files
  • Custom frontend scripts
  • Every .js file across the website

The VisitorTracker campaign appended a function named visitorTracker_isMob() to JavaScript files and interacted with a secondary backdoor to load an external exploit-kit resource. Sucuri reported that most of the affected sites it detected during that campaign used WordPress.

Useful historical indicators include:

visitorTracker_isMob
_mauthtoken
navigator.userAgent
screen.width
document.cookie.indexOf
document.addEventListener("click"

Indicators are not universal signatures. Modern malware frequently changes variable names and obfuscation.

Example of a fake WordPress-looking JavaScript file

(function () {
    function isMobileVisitor() {
        return /Android|iPhone|iPad|iPod|Mobile/i.test(
            navigator.userAgent || ""
        );
    }

    document.addEventListener(
        "click",
        function () {
            if (isMobileVisitor()) {
                console.warn(
                    "Click-triggered redirect blocked."
                );

                // Disabled:
                // location.href =
                //     "hxxps://spam-domain[.]example/offer";
            }
        },
        { once: true }
    );
})();

An attacker could save code with this behavior under a legitimate-looking filename such as style.wp.includes.js or inject it into an existing theme or plugin bundle. Waiting for the first click makes automated detection and manual reproduction more difficult.


7. The wp_options Database Table

File scans do not find malware that exists only in the database.

Inspect suspicious values in:

wp_options.option_value

Potential locations include:

  • Widget settings
  • Theme options
  • Header and footer scripts
  • Page-builder settings
  • Custom CSS or JavaScript
  • Cached transients
  • Unknown autoloaded options
  • Serialized configuration records

Sucuri documented a mobile redirect to the chickenkiller domain stored in a hex-encoded serialized value inside wp_options. The specific option ID varied between infections.

That case is important because a search for a visible spam domain could fail: the malicious string had been encoded.

Safe serialized-value example

a:1:{
    s:7:"padding";
    s:102:"DEMO_ONLY|navigator.userAgent|Android|iPhone|
    _mauthtoken|hxxps://spam-domain[.]example|NO_REDIRECT";
}

A real database payload may appear as one long serialized value, use hexadecimal escape sequences, or be mixed with legitimate theme or widget settings. Do not edit serialized data without a backup because incorrect string lengths can corrupt the option.

SQL queries for investigating the database

SELECT option_id, option_name, autoload
FROM wp_options
WHERE option_value REGEXP
'_mauthtoken|visitorTracker_isMob|navigator\\.userAgent|
screen\\.width|window\\.location|location\\.href';
SELECT ID, post_type, post_title
FROM wp_posts
WHERE post_content REGEXP
'_mauthtoken|navigator\\.userAgent|screen\\.width|
window\\.location|document\\.addEventListener';

Replace wp_ with the actual database prefix. These queries are investigation starting points only; legitimate code can contain some of the same strings.


8. Posts, Pages, Comments and Testimonials

Malicious JavaScript can be stored in content rather than configuration.

Inspect:

wp_posts.post_content
wp_comments.comment_content
Page-builder data
Testimonials
Reusable blocks
Custom post types
HTML widgets

The 2023 bogus URL-shortener campaign was commonly found inside WordPress pages, posts, testimonials and comments, in addition to legitimate JavaScript files.

This matters on sites where:

  • Contributors can submit content
  • Comments allow unexpected HTML
  • A vulnerable page builder is installed
  • Imported content contains scripts
  • An attacker obtained administrator access

9. Uploads and Cache Directories

Check:

/wp-content/uploads/
/wp-content/cache/
/wp-content/upgrade/

A normal uploads directory should not generally execute PHP.

Look for:

  • PHP files inside year/month media folders
  • .ico files containing PHP
  • Double extensions
  • Hidden dotfiles
  • Fake image files
  • Random directories
  • Recently regenerated cache files containing injections

Cleaning the cache alone is not enough. If a malicious source file or database record remains, the cache will rebuild the infected output.


10. External and Third-Party Scripts

The malware is not always physically stored in WordPress.

A compromised external resource can selectively serve malicious code to mobile visitors.

Possible sources include:

  • Analytics scripts
  • Advertisement networks
  • Trust badges
  • Chat widgets
  • Old CDN files
  • Tag-management containers
  • Externally hosted libraries
  • Compromised vendor accounts

Sucuri documented a compromised website-reputation badge that served additional malicious JavaScript only to mobile user agents and used a cookie to reduce repeated redirects.

When the files and database look clean, inspect every third-party request loaded by the affected page.


Historical Mobile Redirect Malware Samples

Mobile-only WordPress redirects are not one malware family. They are a behavior shared by many unrelated campaigns.

BaDoink mobile redirect

This campaign targeted visitors using phones and tablets while filtering by IP address and session conditions. It was designed so that a redirected visitor might not see the behavior again for many hours.

Chickenkiller database injection

This sample was stored in wp_options, used serialized data and hex encoding, and redirected targeted mobile visitors to an external destination.

VisitorTracker

This campaign injected visitorTracker_isMob() into JavaScript files and used a secondary backdoor to load external malicious content.

Screen-width redirects

Some samples used a basic condition based on a screen width of 480 pixels or less. The method was simple but effective against many phones at the time.

_mauthtoken redirects

This long-running family checked mobile user agents and used the _mauthtoken cookie to prevent repeated execution. Obfuscation changed between variants, but the cookie name became a useful historical indicator.

Bogus URL-shortener and AdSense campaign

This campaign evolved through several variants. It used external scripts, fake WordPress-style JavaScript files, database injections, mobile detection, click-based execution and server-side user-agent filtering.

Sucuri reported detecting strains of the broader campaign on more than 24,000 websites during the period covered by its 2023 analysis.

These examples should not be treated as a complete list. Attackers continuously change domains, filenames, cookies, variables and obfuscation while reusing the same underlying conditional-redirect techniques.


How to Confirm a Mobile-Only Redirect

Before editing files, collect evidence.

Step 1: Test from a clean session

Use:

  • A real phone
  • Private or incognito browsing
  • Cleared site cookies
  • A different network
  • Mobile data instead of the office Wi-Fi
  • A search-engine result instead of opening the URL directly

Record:

  • The affected URL
  • The destination URL
  • The time
  • The device and browser
  • Whether the visit came from Google
  • Whether the redirect happened before or after a tap
  • Whether a second visit behaved differently

Do not repeatedly interact with an unknown landing page. Close it after recording the destination.


Step 2: Compare Desktop and Mobile HTTP Responses

Test only websites you own or are authorised to investigate.

A desktop request:

curl -I https://example.com/

A mobile-style request:

curl -I \
  -A "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome Mobile Safari/537.36" \
  https://example.com/

Compare:

  • Status code
  • Location header
  • Cookies
  • Response size
  • Cache headers
  • Server behavior

A pattern such as this is significant:

Desktop request: 200 OK
Mobile request: 302 Found
Location: external-domain.example

It strongly suggests that the server is making a decision based on the request, especially when the result can be reproduced from multiple clean sessions.


Step 3: Review Access and SSL Logs

Logs can answer questions that the WordPress dashboard cannot.

Search for:

  • 301, 302, 307 and 308 responses
  • Requests from mobile user agents
  • Suspicious PHP files
  • Unknown POST requests
  • File-manager paths
  • Shell filenames
  • Requests immediately before files changed
  • Access from unfamiliar IP addresses

In my case study, the access logs also showed requests targeting known shell-style paths. The combination of a mobile-only 302 response and reachable shell-related files showed that the redirect was only one part of a larger compromise.


Step 4: Inspect .htaccess at Every Relevant Level

Check:

  • The WordPress document root
  • The directory above the document root
  • wp-admin
  • wp-includes
  • wp-content
  • Upload and plugin subdirectories
  • Other websites under the same hosting account

Attackers sometimes place a parent-level rule that affects multiple domains.

Compare each file against an expected clean configuration rather than deleting every unfamiliar rule. Hosting platforms, caching plugins and security services may add legitimate directives.


Step 5: Compare WordPress Core Files

Use a clean package matching the installed WordPress version.

WP-CLI can help identify modified or unexpected core files:

wp core verify-checksums

A successful checksum comparison does not prove that the entire site is clean. It does not validate:

  • Themes
  • Premium plugins
  • Database content
  • Uploads
  • .htaccess
  • wp-config.php
  • Server-level cron jobs
  • Other sites in the hosting account

Step 6: Search Files for Behavioral Indicators

Search for behavior, not only domains.

grep -RInE \
'HTTP_USER_AGENT|navigator\.userAgent|screen\.width|_mauthtoken|visitorTracker_isMob|document\.addEventListener|window\.location|location\.href' \
wp-content wp-config.php .htaccess 2>/dev/null

Every match must be reviewed manually.

Legitimate responsive scripts, analytics tools and device-detection plugins can contain similar strings. A keyword result is evidence to investigate, not automatic proof of malware.


Step 7: Search the Database

Search for:

<script
iframe
navigator.userAgent
window.location
document.cookie
screen.width
Unknown external domains
Long encoded values
Unexpected serialized data

Review:

  • Options
  • Posts
  • Comments
  • User metadata
  • Page-builder records
  • Widget data
  • Custom tables created by plugins

Always export a database backup before modifying serialized values. Incorrect manual replacement can corrupt length values and break the stored configuration.


Step 8: Review Administrator Accounts and Credentials

Check for:

  • Unknown administrators
  • Recently created users
  • Changed administrator email addresses
  • Application passwords
  • Unfamiliar API keys
  • Compromised hosting users
  • Old FTP accounts
  • Reused passwords
  • Exposed database-management tools

Deleting the redirect while an attacker still controls an administrator or hosting account will not produce a lasting cleanup.


How to Remove WordPress Mobile Redirect Malware Properly

A complete cleanup has four goals:

  1. Stop the redirect
  2. Remove every malicious component
  3. Eliminate the attacker’s access
  4. Close the original entry point

Preserve evidence first

Before making changes:

  • Back up the files
  • Export the database
  • Save access and error logs
  • Record suspicious filenames and timestamps
  • Save redacted screenshots
  • Record the redirect chain

Evidence can help identify how the compromise occurred and whether other websites are affected.

Remove the visible redirect

Depending on the infection, this may require cleaning:

  • .htaccess
  • wp-config.php
  • Theme files
  • Plugin files
  • JavaScript
  • Database records
  • External script references

Do not stop after the symptom disappears.

Replace compromised software with clean copies

Replace WordPress core with an official clean copy.

Replace plugins and themes from trusted sources rather than copying individual clean-looking lines into modified files.

Do not reinstall nulled plugins or themes. They may contain the original backdoor.

Find and remove persistence

Search the complete hosting account for:

  • Web shells
  • Backdoors
  • Fake plugins
  • Hidden administrators
  • Malicious cron jobs
  • PHP in uploads
  • Database triggers
  • Modified parent directories
  • Malware in sibling websites
  • Stolen deployment keys
  • Compromised control-panel users

Rotate credentials

Change:

  • WordPress administrator passwords
  • Hosting control-panel password
  • SFTP and SSH credentials
  • Database password
  • Email credentials connected to recovery
  • CDN and DNS credentials
  • API keys
  • WordPress salts

Credential rotation should happen after unauthorised access has been removed, otherwise the attacker may capture the new credentials.

Patch the entry point

Update or remove:

  • Vulnerable plugins
  • Vulnerable themes
  • Abandoned extensions
  • Nulled software
  • Unused administrator accounts
  • Public file managers
  • Unprotected staging sites
  • Old WordPress installations
  • Other compromised sites in the account

A redirect is an outcome of a compromise. The malicious rule itself is rarely the original vulnerability.


Why the Mobile Redirect Keeps Coming Back

Reinfection usually means one of these problems remains:

  • A hidden shell can rewrite the cleaned file
  • A scheduled job restores the malware
  • Another infected website shares the same account
  • A fake plugin reloads the payload
  • A database record regenerates JavaScript
  • An attacker still has valid credentials
  • The vulnerable plugin was never patched
  • Server-level malware exists outside the WordPress directory
  • A cache rebuilds from an infected source
  • A compromised third-party script remains embedded

Repeatedly deleting .htaccess is not a security strategy.

It treats the most visible symptom while leaving the attacker’s access intact.


Can Mobile Redirect Malware Hurt SEO?

Yes.

A mobile-only infection can harm search performance even when the website looks normal to its owner.

Possible consequences include:

  • Visitors immediately leaving the site
  • Loss of trust and conversions
  • Search engines discovering malicious destinations
  • Browser or antivirus warnings
  • Spam pages appearing in search results
  • Crawling and indexing disruption
  • Damage to branded search results
  • Advertising-account suspension
  • Hosting-account suspension
  • Search Console security warnings

The exact impact depends on what search engines and security systems observe, how long the compromise remains active, and whether spam content or redirects become indexed.

After cleanup:

  1. Confirm desktop and mobile responses are clean
  2. Test important landing pages
  3. Clear every caching layer
  4. Review Google Search Console security issues
  5. Check indexed pages for unexpected content
  6. Submit affected URLs for recrawling where appropriate
  7. Continue monitoring logs and file changes
  8. Watch branded search results for spam

Do not request a review until the backdoors and entry point have been addressed.


How to Prevent Another Mobile Redirect Infection

The most effective controls are straightforward:

  • Keep WordPress, themes and plugins updated
  • Remove unused extensions
  • Avoid nulled software
  • Use unique passwords and multi-factor authentication
  • Restrict administrator access
  • Disable PHP execution in uploads where appropriate
  • Monitor file changes
  • Keep off-server backups
  • Review administrator users regularly
  • Protect staging sites
  • Use least-privilege file permissions
  • Monitor access logs
  • Scan the entire hosting account, not only one domain
  • Maintain an inventory of authorised third-party scripts

No security plugin can compensate for abandoned vulnerable software, exposed credentials or an active server-level backdoor.


Frequently Asked Questions

Why does my WordPress site redirect on mobile but not desktop?

The malicious code is probably applying conditions before redirecting. It may check the browser user agent, screen width, referrer, IP address, cookies or whether the visitor is logged in.

Can a WordPress plugin cause a mobile redirect without malware?

Yes. A legitimate mobile-redirection, translation, advertising or caching plugin can be misconfigured. However, an unexplained redirect to a spam or unrelated external website should be treated as a possible compromise until proven otherwise.

Is mobile redirect malware always inside .htaccess?

No. It can exist in PHP files, JavaScript, themes, plugins, must-use plugins, WordPress core directories, database content, uploads, scheduled jobs or third-party scripts.

Why can’t I reproduce the redirect?

The malware may exclude logged-in users, remember your IP address, set a cookie, require a Google referrer, wait for a click or execute randomly. Test using a clean session, a different network and both desktop and mobile user agents.

Is deleting .htaccess enough?

Usually not. Deleting the malicious rule may stop the immediate redirect, but it does not remove the backdoor, vulnerable plugin or stolen credential that allowed the attacker to create it.

Can the malware be hidden in the WordPress database?

Yes. Documented infections have been found in wp_options, posts, pages, comments, testimonials, widgets and page-builder data.

Why does the destination keep changing?

The WordPress code may contact a remote traffic-distribution system. That system chooses the destination based on device, country, campaign availability or expected revenue.

Can clearing the WordPress cache fix the redirect?

Clearing the cache may temporarily remove infected generated output, but the redirect will return if its original source remains in a file, database record or external script.

Should I restore a backup?

A known-clean backup can help, but it is not a complete solution by itself. The vulnerable component, compromised credentials or server-level backdoor may still exist and reinfect the restored site.

How do I know the site is completely clean?

A proper verification should include file integrity, database inspection, user review, log analysis, backdoor searches, vulnerability remediation, credential rotation and repeated mobile and desktop testing from clean sessions.


Final Takeaway

A WordPress website that redirects only on mobile is not experiencing a normal redirect problem.

It is often dealing with malware specifically designed to remain hidden from the person managing the site.

The malicious behavior may be controlled by .htaccess, PHP, JavaScript, database content, a hidden plugin, an external script or a remote traffic-distribution system. It may execute once per IP, only after a Google visit, only after a tap or only when the visitor has no tracking cookie.

That is why mobile redirect investigations must go beyond deleting one suspicious line.

The visible redirect must be removed, but the real work is finding:

  • How the attacker gained access
  • What persistence they installed
  • Which files and database records were modified
  • Whether other sites in the account are infected
  • What must be changed to prevent reinfection

I have manually investigated and cleaned more than 4,500 hacked WordPress websites since 2018. In mobile redirect cases, the difference between a temporary fix and a proper recovery is almost always the depth of the investigation.

Need Help With a WordPress Mobile Redirect?

When your site redirects on phones, sends visitors to spam, or becomes reinfected after cleanup, I can investigate the files, database, logs and persistence mechanisms to identify the real source of the compromise.

Request a manual WordPress malware investigation

Evidence-led companion pages

Related malware research

Practical next steps

Need help applying this to your site?

Choose the level of help that fits where you are now. Start with professional cleanup, request a preliminary scan, or learn the process yourself.

Get malware removal help

Support My WordPress Security Research ☕

If this work helped you and you would like to support future malware investigations and practical guides, you can buy me a coffee. It is completely optional—everything remains free to read.

Buy me a coffee

Continue reading

Related blog

About the author

MD Pabel

Independent WordPress security specialist with first-hand experience across more than 4,500 hacked-site cleanups since 2018.

Experience and methodology

Community

Comments

Loading comments...

Join the discussion

Leave a comment

Your email address will not be published. Comments may be held for review before they appear.