
How to fix WordPress redirect hacks?
- Sajjad
- WordPress, Security
- 15 Sep, 2026
To fix a WordPress redirect hack, you need to find and remove every piece of injected code that sends visitors to another site, then close the hole the attacker used to get in. In practice that means backing up the infected site, checking your .htaccess file, comparing core files against clean copies, searching the database for injected scripts and URLs, removing rogue admin users and files, and then changing every password and salt. Skipping any one of those steps is the most common reason a redirect comes back a day later.
Redirect hacks are frustrating because they often hide from you. Many only trigger for visitors arriving from Google, for mobile users, or for people who are not logged in, so the site looks perfectly normal when you check it from your dashboard. This guide walks through how redirect hacks work, how to confirm you have one, and a step-by-step cleanup process you can follow, including the WP-CLI and SQL commands that make the job faster.
What Is a WordPress Redirect Hack?
A redirect hack is a type of compromise where an attacker injects code into your site that sends some or all of your visitors to a different domain. The destination is usually a spam page, a fake "you won a prize" survey, a scam tech-support page, a malicious download, or an ad network that pays the attacker for traffic.
The attacker is not usually interested in your site itself. They want your traffic and your search engine reputation. A well-ranked, trusted domain is valuable because visitors click on it without hesitation, and browsers and email filters are less suspicious of it.
Common Types of Redirects
Redirect malware tends to fall into a few patterns:
- Server-level redirects: Rules added to
.htaccess(on Apache or LiteSpeed) or server configuration that redirect based on the referrer or user agent. - PHP redirects: Code injected into theme files, plugin files,
wp-config.php, or core files such asindex.phporwp-blog-header.phpthat callsheader()orwp_redirect()under certain conditions. - JavaScript redirects: Scripts injected into posts, widgets, theme options, or plugin settings stored in the database, often obfuscated with
eval(),atob()orString.fromCharCode(). - Conditional redirects: Any of the above, but only firing for search engine referrers, mobile devices, first-time visitors (tracked with a cookie), or non-logged-in users.
That last category is why you may hear "my customer says the site redirects, but I can't reproduce it." The malware is designed to hide from the site owner.
Signs Your WordPress Site Has a Redirect Hack
Before you start cleaning, confirm what you are dealing with. Typical signs include:
- Visitors report being sent to spam, gambling, pharmacy, or scam sites.
- The redirect only happens when you click your site from Google search results, not when you type the URL directly.
- Mobile visitors get redirected but desktop visitors do not.
- Google Search Console shows a security issue or "Deceptive pages" warning.
- Chrome shows a red warning page before loading your site.
- Your hosting provider has suspended the account or sent a malware notice.
- You see unfamiliar admin users, plugins, or files you did not create.
- Your
siteurlorhomevalue has changed to a domain you don't recognise.
How to Reproduce a Conditional Redirect
To see what visitors see, log out of WordPress and use a private browsing window. You can also simulate a Google referrer and a mobile user agent with curl from your computer:
curl -sI -A "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)" \
-e "https://www.google.com/" \
https://example.com/
Look at the response. A 301, 302 or 307 status with a Location header pointing to an unknown domain confirms a server-side redirect. If the response is a normal 200, fetch the HTML and look for injected scripts:
curl -s -A "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)" \
-e "https://www.google.com/" \
https://example.com/ | grep -iE "eval\(|atob\(|fromCharCode|window\.location|document\.location"
Free external scanners such as Sucuri SiteCheck can also flag known redirect payloads from the outside, though they can't see everything on the server.
Before You Start: Prepare Safely
A few precautions will save you a lot of trouble:
-
Take a full backup of the infected site: Back up files and the database even though they are compromised. If you delete something important during cleanup, you'll want a copy to recover it from. Keep this backup clearly labelled as infected and do not restore it later.
-
Put the site in maintenance mode if possible: This protects visitors while you work. Many hosts let you restrict access by IP address, or you can use a maintenance mode plugin once you trust the admin area.
-
Get SSH or SFTP access: Cleaning through the WordPress dashboard alone is not reliable, because the malware may be running in the same environment. Direct file access and WP-CLI are far more dependable.
-
Check your local computer: If your FTP credentials were stolen from your own machine, cleaning the server won't help for long. Run a reputable antivirus scan on any computer used to manage the site.
Step 1: Check the .htaccess File
On Apache and LiteSpeed servers, .htaccess is one of the first places attackers put redirect rules. Open the file in your site's root directory (and check for additional .htaccess files in subfolders like wp-content and wp-content/uploads).
A standard WordPress .htaccess for a single site looks like this:
# BEGIN WordPress
<IfModule mod_rewrite.c>
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]
</IfModule>
# END WordPress
Suspicious additions often look like rules that check the referrer or user agent before redirecting, for example a RewriteCond %{HTTP_REFERER} line mentioning google or bing, followed by a RewriteRule that sends traffic to an external domain with [R=302,L]. Remove any rules you didn't add yourself or that don't belong to a plugin you trust (caching and security plugins add their own clearly labelled blocks).
To find every .htaccess file on the account quickly:
find /var/www/example.com -name ".htaccess" -type f -exec ls -la {} \;
If you are on Nginx, .htaccess is ignored, but check your server blocks in /etc/nginx/sites-enabled/ for any return 301 or rewrite lines you didn't create.
Step 2: Verify WordPress Core Files
Attackers frequently modify core files because owners rarely look at them. WP-CLI can compare every core file against the official checksums from WordPress.org:
cd /var/www/example.com
wp core verify-checksums
Any file that is reported as modified or that "should not exist" deserves attention. The cleanest fix is to reinstall core without touching wp-content or wp-config.php:
wp core download --skip-content --force
This overwrites wp-admin, wp-includes, and the root core files with fresh copies of your current version. If WP-CLI isn't available, download the same WordPress version from WordPress.org, delete wp-admin and wp-includes on the server, and upload the fresh folders along with the root .php files (again, leave wp-config.php and wp-content alone).
Step 3: Check Plugins and Themes
Plugins and themes are the most common entry point and the most common hiding place. WP-CLI can verify plugins hosted on WordPress.org against their published checksums:
wp plugin verify-checksums --all
Premium plugins and themes can't be verified this way, so the safest approach is to delete them and reinstall fresh copies from the vendor's official site.
While you are here:
- Delete any plugin or theme you don't recognise or no longer use.
- Delete nulled or pirated plugins and themes entirely. They are a very common source of backdoors.
- Update everything to the latest version with
wp plugin update --allandwp theme update --all. - Check the
wp-content/mu-pluginsfolder. Must-use plugins load automatically and don't appear in the normal plugin list, which makes them a popular hiding spot.
wp plugin list --status=must-use
ls -la wp-content/mu-plugins/
Step 4: Search for Malicious Code in Files
After core, plugins, and themes have been replaced, you still need to check anything custom, such as your child theme and files in wp-content/uploads.
The uploads folder should contain media, not PHP. Any PHP file there is a red flag:
find wp-content/uploads -type f -name "*.php"
Search the rest of wp-content for common obfuscation patterns:
grep -rlE "eval\(base64_decode|gzinflate\(|str_rot13\(|assert\(\\\$_|preg_replace\(.*/e" wp-content/
Look for files changed recently, which can reveal what the attacker touched:
find . -type f -name "*.php" -mtime -14 -printf "%TY-%Tm-%Td %TH:%TM %p\n" | sort -r
Keep in mind that legitimate plugins sometimes use base64_decode for normal reasons, so treat these results as leads to review rather than a list of files to delete blindly. Also check wp-config.php manually, since it is not covered by core checksums. Compare it with the default wp-config-sample.php and remove anything unfamiliar, especially include or require lines pointing to odd files.
Step 5: Clean the Database
Many redirect hacks live entirely in the database, injected into posts, widgets, or plugin settings. Start by checking the site URLs:
wp option get siteurl
wp option get home
If either points to a domain you don't own, fix it:
wp option update siteurl "https://example.com"
wp option update home "https://example.com"
Next, search post content for injected scripts. Replace wp_ with your actual table prefix if it's different:
SELECT ID, post_title, post_type
FROM wp_posts
WHERE post_content LIKE '%<script%'
OR post_content LIKE '%eval(%'
OR post_content LIKE '%fromCharCode%'
OR post_content LIKE '%atob(%';
Then check the options table, where widgets, theme settings, and plugin settings are stored:
SELECT option_id, option_name
FROM wp_options
WHERE option_value LIKE '%<script%'
OR option_value LIKE '%eval(%'
OR option_value LIKE '%fromCharCode%';
You can run these through WP-CLI with wp db query "..." if you don't have phpMyAdmin. Some results will be legitimate, for example an analytics snippet you added deliberately or a plugin that stores inline scripts. Review each result before editing, and fix injected content by editing the post in the block editor or by carefully updating the specific row.
If the attacker injected the same domain everywhere, wp search-replace can help, but always run it with --dry-run first:
wp search-replace "https://malicious-domain.example" "" --all-tables --dry-run
Be careful with search-replace on script fragments. Removing a domain alone may leave broken <script> tags behind, so check a few affected rows manually afterwards.
Step 6: Remove Rogue Users and Scheduled Tasks
Attackers often create a hidden administrator account so they can get back in after you clean up. List all administrators:
wp user list --role=administrator --fields=ID,user_login,user_email,user_registered
Delete any account you don't recognise and reassign its content to a real user:
wp user delete 42 --reassign=1
Also check for scheduled tasks (cron events) that re-infect the site on a timer:
wp cron event list --fields=hook,next_run_relative,recurrence
Hooks with random-looking names that don't match any installed plugin are worth investigating. Search your files for the hook name to see what registers it.
Step 7: Reset Passwords, Keys, and Salts
Once the site is clean, assume every credential has been exposed. Change:
- All WordPress administrator and editor passwords.
- Your hosting control panel, SFTP, and SSH passwords.
- The database user password (update
DB_PASSWORDinwp-config.phpto match). - Any API keys stored in plugin settings.
Then regenerate the security keys and salts, which logs every user out, including the attacker if they still have an active session cookie:
wp config shuffle-salts
If you prefer to do it manually, get fresh values from the official WordPress.org secret key generator and replace the eight define() lines in wp-config.php.
Step 8: Request a Review and Monitor
If Google flagged your site, open Google Search Console, go to Security & Manual Actions > Security issues, confirm the problems are fixed, and click Request Review. Reviews for malware issues usually take anywhere from a day to a few days. If your host suspended the account, contact them with a summary of what you cleaned.
Over the following weeks, keep an eye on things:
- Re-run
wp core verify-checksumsandwp plugin verify-checksums --allperiodically. - Watch for new admin users or unexpected file changes.
- Use a security plugin with file change detection and malware scanning, such as Wordfence, Sucuri Security, or Solid Security.
- Retest with the
curlcommands above using search referrers and mobile user agents.
How to Prevent Redirect Hacks in the Future
Cleaning is only half the job. The redirect will return if the original weakness is still there. The most important preventive steps are:
-
Keep everything updated: Outdated plugins and themes are the most common way attackers get in. Enable automatic updates for plugins you trust, and remove anything abandoned.
-
Use strong, unique passwords and two-factor authentication: This protects against credential stuffing and brute-force attacks on
wp-login.php. -
Disable file editing in the dashboard: Adding the line below to
wp-config.php, above the "That's all, stop editing!" comment, stops anyone with admin access from editing theme and plugin files through Appearance > Theme File Editor.
define( 'DISALLOW_FILE_EDIT', true );
- Block PHP execution in uploads: On Apache 2.4, place this
.htaccessinsidewp-content/uploads:
<FilesMatch "\.(php|phtml|php[0-9]|phar)$">
Require all denied
</FilesMatch>
On Nginx, add a rule inside your server block:
location ~* ^/wp-content/uploads/.*\.(php|phtml|phar)$ {
deny all;
}
-
Set correct file permissions: Directories should generally be
755and files644, withwp-config.phptighter (640or600depending on how your server runs PHP). -
Keep regular, off-site backups: A clean backup from before the infection can turn a long cleanup into a short restore, as long as you still fix the underlying vulnerability afterwards.
-
Use a web application firewall: A firewall from Wordfence, Sucuri, or Cloudflare can block many exploit attempts before they reach WordPress.
FAQ: WordPress Redirect Hacks
Many redirect hacks are conditional. They check the referrer, device type, or login cookie and only redirect visitors coming from search engines, using mobile devices, or who are not logged in. This is deliberate, so the site owner doesn't notice.
A security plugin can help find infected files, but it rarely finds everything, especially code hidden in the database or in must-use plugins. Use it alongside a manual check of .htaccess, core files, the database, users, and cron events.
Restoring a clean backup from before the infection removes the malicious code, but it also restores the original vulnerability. You still need to update plugins, change passwords, and fix whatever let the attacker in, or the hack will likely return.
Usually because a backdoor file, hidden admin user, scheduled cron event, or vulnerable plugin was missed. Reinfection can also happen if your hosting or FTP credentials were stolen and not changed.
Search the wp_posts and wp_options tables for script tags, eval, atob, and fromCharCode using SQL queries or WP-CLI. Review each result carefully, since some plugins store legitimate scripts in the database.
Yes. Google may show a warning in search results, add a security issue in Search Console, or drop rankings for affected pages. Once the site is clean, request a review in Search Console to have warnings removed.
If you're not comfortable with SSH, WP-CLI, or database queries, or the site handles payments or personal data, hiring a reputable malware removal service is a sensible choice. Many security companies offer cleanup with a guarantee period.
Conclusion
A WordPress redirect hack can feel alarming, especially when you can't reproduce it yourself, but the cleanup follows a clear pattern. Back up first, then work through .htaccess, core files, plugins and themes, custom code and uploads, the database, users, and scheduled tasks. Finish by replacing every password and salt so any stolen access stops working.
The step that matters most in the long run is closing the door the attacker walked through. Keep plugins and themes updated, remove anything you don't use, block PHP in uploads, and keep reliable off-site backups. With those habits in place, a redirect hack is far less likely to happen again, and if it does, you'll be able to recover quickly.


