DEV Community

Cover image for How to Fix a WordPress Site Redirecting to Spam
Decodeinfy
Decodeinfy

Posted on Originally published at ownertrail.decodeinfy.in on

How to Fix a WordPress Site Redirecting to Spam

If your WordPress site sends visitors to spam pages, an attacker has added conditional redirect code to your site files or database. Here is how to reproduce the issue safely, locate the code, remove it, and find out how it got in.

Why WordPress sites redirect visitors to spam sites

When a WordPress site gets hacked with redirect malware, the redirect rarely happens for every visitor. If every page redirected immediately, the site owner would spot the problem right away. Attackers use conditional rules so the site functions normally for you while redirecting specific groups of visitors to spam or scam websites.

Malicious scripts evaluate HTTP request headers sent by a visitor's browser. They check two key details:

  • User-Agent: This identifies the device and browser. Attackers often target mobile visitors on iOS or Android devices while leaving desktop users untouched.
  • HTTP Referer: This records the page the visitor came from. The script checks if the visitor arrived from search engines like Google, Bing, or Yahoo.

When a real user searches for your business on a smartphone and clicks your site in Google search results, their browser sends a mobile User-Agent and a Google HTTP Referer header. The malicious script detects both, overrides your normal site output, and issues an HTTP 301 or 302 redirect to an external URL. If you open a browser and type your URL directly into the address bar, there is no search referrer, so the page loads normally.

This mechanism is closely related to search engine cloaking, similar to the techniques explained in our guide on the Japanese keyword hack and cloaking, where attackers serve different content to search engines and normal visitors.

How to safely test and reproduce the redirect

Testing conditional redirects by tapping links on your phone can be frustrating. Web browsers cache redirect responses aggressively, meaning your phone might keep redirecting even after you clean the site, or fail to show the redirect because you visited the site directly earlier.

The safest way to reproduce and inspect the redirect is using command-line tools like curl, which send requests without executing script payloads or caching headers.

Open a terminal on your computer and run this command to inspect your homepage headers while simulating a mobile visitor arriving from Google:

curl -I -A "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15" -e "https://www.google.com/" https://your-site.com/
Enter fullscreen mode Exit fullscreen mode

Examine the first line of the output:

  • A clean site returns HTTP/2 200 OK or HTTP/1.1 200 OK.
  • A compromised site returns HTTP/2 302 Found or 301 Moved Permanently, followed by a Location: header listing an unfamiliar domain name.

You can also use Google Chrome Developer Tools. Open a new Incognito window, open Developer Tools (F12), switch to the Device Toolbar to select an iPhone or Android preset, and navigate to the Network tab. Under Network Conditions, uncheck "Use browser default" for User-Agent and set custom request headers to test how your server responds to search engine referrers.

Where malicious redirect code hides on your server

Malicious code must run early in the loading process to redirect visitors before your page finishes rendering. Attackers usually place code in one of five locations:

  1. The .htaccess file: On Apache web servers, attackers insert rewrite rules near the top of .htaccess. These rules inspect the incoming request for search referrers or mobile strings and redirect matching requests directly at the web server level before PHP even runs.
  2. Core startup files: Attackers alter files like index.php, wp-config.php, or wp-settings.php. They insert obfuscated PHP functions like eval(base64_decode(...)) or gzuncompress() near the top of the file. Performing a regular WordPress file integrity check helps detect core files that differ from official release versions.
  3. Theme and plugin files: Code can be added to your active theme's functions.php file or hidden deep inside an installed plugin.
  4. Standalone PHP files in upload folders: Attackers often drop unauthorized PHP scripts into media directories. Finding PHP files in your WordPress uploads folder is a clear signal of leftover backdoor scripts used to maintain unauthorized access.
  5. The WordPress database: Malicious JavaScript can be injected into the wp_options table inside fields like siteurl, home, or auto-loaded option entries designed to inject scripts into your site header or footer.

How to clean malicious redirects from your site

Cleaning a site requires systematically replacing code files rather than deleting individual lines by hand, because manual edits often leave hidden backdoor files behind.

Follow these steps to clean your installation:

  1. Create a backup: Save a complete copy of your site files and database for reference before making changes.
  2. Reset core files: Download a fresh zip archive of your exact WordPress version from WordPress.org. On your server, replace the wp-admin and wp-includes folders entirely. Replace root files like index.php, wp-activate.php, and wp-blog-header.php. Inspect wp-config.php by hand to verify that every line belongs there.
  3. Replace .htaccess: Delete your current .htaccess file and create a new one containing standard WordPress rewrite rules.
  4. Reinstall plugins and themes: Delete all folders inside wp-content/plugins/ and reinstall fresh copies from official sources. Delete and reinstall your theme folders under wp-content/themes/.
  5. Clean media directories: Search the wp-content/uploads/ directory for any files ending in .php, .php5, or .htaccess and delete them. Upload folders should contain media files like images, videos, and PDFs, not executable code.
  6. Check database options: Log into phpMyAdmin or use WP-CLI to inspect your database. Check the wp_options table to ensure siteurl and home match your domain. Inspect header and footer settings added by options plugins to remove embedded JavaScript redirects.

Finding out how the unauthorized access happened

Cleaning your site removes the current redirect, but if you do not identify the entry point, the site can be reinfected. Work through these steps to investigate how access was gained:

Check server access logs: Request your web server's HTTP access logs from your hosting provider. Search for POST requests made around the time the redirect first appeared. Pay close attention to requests sent directly to files inside wp-content/uploads/ or repeated access to xmlrpc.php.

Review file modification dates: Use your FTP client or hosting file manager to sort files by modification date. If multiple files across different plugin or core folders share the exact same recent timestamp, open those files to inspect recent changes.

Audit user accounts and credentials: Check Users > All Users in your WordPress dashboard for unfamiliar administrator accounts. Change all passwords associated with the site, including WordPress admin accounts, database credentials, FTP/SFTP accounts, and hosting control panel logins.

Check plugin supply chain status: Unpatched vulnerabilities in outdated plugins or sudden changes in plugin maintainers are common access vectors. Ensure all active plugins receive regular updates from verified developers.

How OwnerTrail alerts you to file changes and supply chain risks

OwnerTrail is a free WordPress plugin available on WordPress.org. It helps site owners monitor changes to their installation so unexpected file modifications can be reviewed immediately.

Every day, OwnerTrail runs automatic checks on your core, plugin, and theme files against official WordPress.org releases. It reads unvouched files on your server to look for the shapes malware takes, and reports any PHP files found in folders like uploads, languages, fonts, upgrade, or backup directories where code does not belong.

To help spot conditional redirects and search engine cloaking early, OwnerTrail fetches your pages as Googlebot. It checks what search engines see versus what normal visitors see, flagging SEO spam hacks and cloaking attempts.

OwnerTrail also monitors plugin ownership and maintenance. It tracks plugin owner changes, checks public SVN commit history for new committers, identifies dormant plugins that suddenly release updates, and alerts you if a plugin has been closed on WordPress.org. Each plugin is assigned a trust score from 0 to 100, and you can enable email notifications with one click to receive alerts when something needs attention.

For added control over file modifications, OwnerTrail includes Code lock, ensuring code on the site can only be changed over FTP, which only a site owner can loosen. From version 1.3.6, when an installed plugin changes hands, its next update is held until the site owner acknowledges the ownership change.

OwnerTrail Pro is coming soon, adding features to approve exact update versions, restore changed files with undo history, quarantine unexpected files, grant time-limited developer access, and set custom policy gates.

        <p><strong>About OwnerTrail.</strong> A free WordPress plugin that watches who controls every plugin on your site, flags plugins WordPress.org has closed, checks your code against WordPress.org's fingerprints, and fetches your pages as Googlebot to catch spam shown only to search engines. It detects; it is not a firewall. <a href="https://wordpress.org/plugins/ownertrail/">Free on WordPress.org</a>.</p>
Enter fullscreen mode Exit fullscreen mode

Related: The Japanese keyword hack: SEO spam that hides from you and shows itself to Google and WordPress file integrity check: was your plugin code changed?.

Top comments (0)