Jay GajjarSenior Software Engineer

WordPress hacked redirect: how to detect and clean it, step by step

WordPress hacked redirect fix: confirm it, clean wp-config, .htaccess, wp_options, mu-plugins, rogue admins and cron, then harden and request a Google review.

By Jay Gajjar11 min read

A WordPress hacked redirect is malware that sends some or all of your visitors to another site, usually spam, scam, fake prize or adult pages. To fix it you need to remove every copy of the injected code (in files, in the database, in scheduled tasks and in hidden admin accounts), close the hole the attacker used, and then ask Google to remove any warning. Deleting the one obvious bad line is rarely enough, because redirect malware almost always leaves a backdoor to reinstall itself.

Quick answer: Take a full backup first. Confirm the redirect with a mobile user agent and a Google referrer. Then check, in this order: siteurl and home in wp_options, every .htaccess file, wp-config.php, core files (verify checksums), plugins and themes (reinstall from clean sources), mu-plugins and drop-ins, PHP files in uploads, injected scripts in the database, unknown administrator accounts and cron events. Change every password, update everything, harden, and request a review in Search Console.

This guide is the order I follow to fix hacked WordPress site redirects. If you would rather not do it yourself, I handle it as a WordPress malware removal job, and a WordPress maintenance plan keeps a cleaned site patched afterwards. It assumes you have hosting access (file manager or SFTP, plus phpMyAdmin or SSH). Where I show WP-CLI commands, run them from the WordPress root directory.

Signs of a WordPress site redirecting to spam

A redirect hack is often hard to see as the site owner, because the malware is written to hide from you. Typical patterns:

  • Visitors arriving from Google are redirected, but typing the address directly works fine.
  • Only mobile visitors are redirected, or only visitors from certain countries.
  • Logged-in administrators never see the redirect.
  • The redirect happens once per visitor (a cookie marks them), so it "goes away" when you try again.
  • Search results show your pages with spam titles in other languages, or Chrome shows a red "Deceptive site ahead" warning.
  • Google Search Console shows a message in Security issues, or sudden new pages in the indexing reports.

If customers tell you the site redirects and you cannot reproduce it, believe them. It is a strong sign of a conditional redirect, not a mistake.

Each symptom points to a likely hiding place, which is a useful shortcut before you work through every step:

Symptom Where to look first
Whole site redirects, even when you type the address siteurl and home in wp_options, then .htaccess (steps 2 and 3)
Only visitors from Google or on mobile are redirected .htaccess rewrite conditions and PHP code that checks the referrer or user agent (steps 3 and 6)
Redirect returns after you delete the bad code A backdoor in uploads, mu-plugins, a fake plugin, an unknown admin or a cron event (steps 7, 9 and 10)
Injected script tags in posts or widgets The database: wp_posts and wp_options (step 8)
Spam pages in Google you never created Core and plugin files, then the indexing reports in Search Console (steps 5, 6 and 12)
Chrome shows "Deceptive site ahead" Search Console Security issues, after the cleanup is finished (step 12)

Step 0: back up everything before you touch anything

Before changing a single file, make a full backup of the infected site: all files and a database export. This feels backwards, but it matters:

  • If cleanup breaks something, you can go back.
  • You keep evidence of what was injected and when, which helps you find how they got in.
  • Your host may restore or suspend the account during the incident, and you want your own copy.

With SSH access:

tar -czf ~/infected-site-files-$(date +%F).tar.gz -C /path/to/site .
wp db export ~/infected-site-db-$(date +%F).sql

Store these outside the public web root and label them clearly as infected. Then check whether you have an older clean backup. Restoring one can save time, but restoring alone does not fix the vulnerability that let the attacker in, so you still need the hardening steps at the end.

Step 1: confirm the WordPress hacked redirect

Use curl to request the page the way a search visitor on a phone would, without following redirects:

curl -sI -A "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148" \
  -e "https://www.google.com/" https://example.com/

A 301 or 302 with a Location: header pointing to a domain you do not recognize confirms a server-side redirect. If you get a normal 200, the redirect may be in JavaScript, so fetch the HTML and search it for unfamiliar script sources:

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 "<script|window.location|document.location"

Also check how Google sees you: the Security issues report in Search Console and Google's Safe Browsing site status (opens in a new tab) page. Note the exact warning; you will need it when you request a review.

Step 2: check siteurl and home in wp_options

Some attacks simply change the WordPress Address and Site Address so every page points to their domain. Check both values:

wp option get siteurl
wp option get home

Or in phpMyAdmin (your table prefix may differ from wp_):

SELECT option_name, option_value
FROM wp_options
WHERE option_name IN ('siteurl', 'home');

If either shows a foreign domain, correct it with wp option update siteurl https://example.com and wp option update home https://example.com. If you cannot log in to fix it, you can temporarily force the values in wp-config.php with define( 'WP_HOME', 'https://example.com' ); and define( 'WP_SITEURL', 'https://example.com' );.

Step 3: inspect every .htaccess file

On Apache and LiteSpeed servers, .htaccess is a favorite place for conditional redirects because rules can check the referrer and user agent. Find all of them, not just the one in the root:

find . -name ".htaccess" -type f

Look for RewriteCond %{HTTP_REFERER} lines matching search engines, RewriteCond %{HTTP_USER_AGENT} lines matching mobile devices, and RewriteRule lines sending traffic to external domains. For a standard single-site install, the WordPress part of the root .htaccess should look like this (WordPress documentation (opens in a new tab)):

# 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

Keep legitimate rules you recognize (caching, security or HTTPS rules your host or plugins added) and remove anything you cannot explain. While you are there, check for .user.ini or php.ini files containing auto_prepend_file or auto_append_file, a trick that loads malicious PHP before every request without touching WordPress files.

Step 4: check wp-config.php

Open wp-config.php and read it from top to bottom. Compare it with wp-config-sample.php from a fresh WordPress download. Red flags:

  • Code above <?php or after the line require_once ABSPATH . 'wp-settings.php';.
  • include or require of files with odd names or in odd locations.
  • Long encoded strings, eval(, base64_decode(, gzinflate( or str_rot13( chains.

Keep your database credentials and any constants you know you added. Remove everything else that does not belong.

Step 5: replace WordPress core files

Check core files against the official checksums:

wp core verify-checksums

Any modified or unexpected file in wp-admin or wp-includes is suspect. The safest fix is to replace all core files with a clean copy of the same version, without touching wp-content:

wp core download --version=$(wp core version) --skip-content --force

Without SSH, download the same version from wordpress.org and upload the wp-admin and wp-includes folders plus the root files (but not wp-config.php and not wp-content), replacing what is there. Delete unknown PHP files in the root that are not part of WordPress.

Step 6: reinstall plugins and themes from clean sources

Do not try to clean plugin files line by line. Reinstall them:

wp plugin verify-checksums --all

This compares plugins against WordPress.org checksums and shows which ones were modified. Plugins from other sources cannot be checked this way. For every plugin and theme:

  • Delete any plugin or theme you do not use. Inactive code can still be exploited.
  • Reinstall WordPress.org plugins fresh (wp plugin install plugin-slug --force).
  • Download premium plugins and themes again from the vendor's account area, never from a "free download" site. Nulled plugins are one of the most common sources of redirect malware.
  • Look for folders in wp-content/plugins that do not match any plugin in your admin list. Malware often installs a fake plugin with a plausible name and hides it from the plugin screen.
  • In custom or child themes you cannot reinstall, check functions.php, header.php and footer.php for injected scripts and encoded code.

Step 7: check mu-plugins, drop-ins and uploads

Three places people forget:

  • wp-content/mu-plugins/: must-use plugins run automatically and do not appear in the normal plugin list. If you did not put a file there (some hosts do), investigate it.
  • Drop-ins in wp-content, such as advanced-cache.php, object-cache.php and db.php. They are legitimate when your caching setup created them, and dangerous when nothing on your site should have.
  • wp-content/uploads/ should contain media, not code. Find PHP files there:
find wp-content/uploads -type f -name "*.php"
find . -type f -name "*.php" -mtime -14 -not -path "./wp-content/cache/*"

The second command lists PHP files changed in the last 14 days, which often points straight at the injected files. Attackers can fake modification times, so treat this as a lead, not proof. You can also search for common obfuscation patterns, remembering that some legitimate plugins use base64_decode too:

grep -rlE "eval\(|gzinflate\(|str_rot13\(|base64_decode\(" --include="*.php" wp-content

Step 8: clean injected scripts from the database

Many redirect infections store a <script> tag in post content, widgets or theme options, so they survive file cleanups. Search the database:

wp db search "<script" --all-tables-with-prefix --one_line
wp db search "eval(" --all-tables-with-prefix --one_line
wp db search "String.fromCharCode" --all-tables-with-prefix --one_line

In SQL, the most common locations are:

SELECT ID, post_title FROM wp_posts WHERE post_content LIKE '%<script%';
SELECT option_name FROM wp_options WHERE option_value LIKE '%<script%';

Not every result is malicious: analytics snippets, embedded forms and page-builder data can contain scripts. Look for unknown domains, encoded strings and scripts injected into many posts at once. Edit or remove the bad entries carefully, and keep that infected database backup in case you remove something legitimate.

Step 9: find rogue admin users

"WordPress hacked admin users added" is one of the most common search terms after an attack, because new administrator accounts are how attackers get back in. List administrators:

wp user list --role=administrator --fields=ID,user_login,user_email,user_registered

Some malware hides its account from the Users screen, so check the database as well:

SELECT u.ID, u.user_login, u.user_email, u.user_registered
FROM wp_users u
JOIN wp_usermeta m ON m.user_id = u.ID
WHERE m.meta_key = 'wp_capabilities'
  AND m.meta_value LIKE '%administrator%';

(Replace both wp_ prefixes, including the one in wp_capabilities, if yours differs.) Delete accounts you do not recognize, reassigning their content to a real user: wp user delete 123 --reassign=1.

Step 10: check cron events and server cron jobs

Malware often schedules a task that reinstalls itself every hour. List WordPress cron events and look for hooks that do not belong to any plugin you use:

wp cron event list --fields=hook,next_run_relative,recurrence

Also check the server's own cron: crontab -l over SSH, or the Cron Jobs section in cPanel. Remove anything that downloads files from unknown addresses or runs PHP files you did not create.

Step 11: lock everything down

Cleaning without hardening invites the same attack back. Do all of this the same day:

  1. Change every password: all WordPress administrators, hosting control panel, SFTP/SSH, database user (then update wp-config.php), and the email account tied to the admin user.

  2. Rotate salts and log everyone out: wp config shuffle-salts invalidates all existing login cookies.

  3. Update WordPress core, all plugins and themes, and remove anything abandoned by its developer.

  4. Run a supported PHP version. If the site is stuck on an old version, plan the upgrade with a PHP 8 upgrade checklist.

  5. Disable the file editor in the dashboard with define( 'DISALLOW_FILE_EDIT', true ); in wp-config.php.

  6. Block PHP execution in uploads. On Apache, add a .htaccess file in wp-content/uploads:

    <FilesMatch "\.(php|phtml|phar)$">
        Require all denied
    </FilesMatch>
    
  7. Set sensible file permissions: typically 755 for folders and 644 for files, with wp-config.php stricter where your host allows.

  8. Turn on two-factor authentication for every administrator, and give other users the lowest role they need.

  9. Add a firewall and file-change monitoring, through your host, a CDN or a security plugin.

  10. Keep automatic off-site backups with enough history to go back weeks, not just days.

This is the core of WordPress security hardening; a monthly WordPress maintenance routine keeps it from drifting.

Step 12: remove the Google blacklist warning

To remove the Google blacklist warning (Chrome's red "Deceptive site ahead" page), the site has to be clean first, then Google has to re-check it. In Search Console, open Security issues, confirm every listed issue is fixed across the whole site, and select Request Review. In the request, describe what the problem was, what you removed, and what you changed to stop it happening again.

Google's Security Issues report help (opens in a new tab) says a review can take from a few days to a few weeks, and asks you not to resubmit before you get a decision. The Chrome warning usually disappears once the review passes.

If the hack created spam pages on your domain, delete them so they return 404 or 410, remove them from your sitemap, and use Search Console's Removals tool for the most visible ones. They drop out of search results as Google recrawls.

When to get professional help

Bring in help if the WordPress hacked redirect comes back after cleaning, if you cannot find the injected code, if the site handles payments or customer data, or if you do not have SSH and database access. A proper WordPress malware removal job covers the same steps as this guide, plus a written note on how the attacker got in, so you know the hole is closed and not just the symptom.

Frequently asked questions

Why does my WordPress site only redirect on mobile?

Redirect malware often targets mobile visitors on purpose, because site owners usually check their site on a desktop while logged in. The code checks the user agent and sometimes the referrer. Test with a mobile user agent and a Google referrer, logged out, to see what visitors see.

Will restoring a backup fix a hacked WordPress site?

A clean backup removes the injected code, but not the weakness that let the attacker in. If you restore without updating plugins, changing passwords and removing the vulnerable code, the site is often reinfected within days. Make sure the backup predates the infection, then harden immediately.

Can a security plugin fix a hacked WordPress site on its own?

A scanner plugin is useful for finding known malware and modified files, but redirect infections often live in the database, server config or cron where plugin scanners have limited reach. Malware can also tamper with plugins running inside the infected WordPress. Use a scanner as one tool alongside the manual checks above.

How long does it take to remove a Google blacklist warning?

After you request a review in Search Console, Google says reviews can take from a few days to a few weeks. Fix every issue across the whole site before requesting, because a failed review means waiting again.

Will the hack hurt my SEO?

A WordPress hacked redirect can hurt SEO, especially if spam pages were indexed or a security warning showed in search results. Most sites recover once the malware and spam pages are removed and the review passes. Fixing it quickly limits the damage.

If your site is redirecting right now and you want it cleaned and secured properly, I can handle it as part of a WordPress malware removal job.