Visit your site and it redirects you to a casino, pharmacy or adult site. Open the admin panel — everything looks fine. Clients coming from Google are complaining. If this sounds familiar, a malicious redirect has been injected into your site. In this article I break down exactly where the redirect code hides, how to find it and how to clean it up manually. If you just noticed the problem and need a first-30-minutes action plan, I have a separate guide to recovering from a hack. This post is the technical cleanup for those ready to dig into the code.

Symptoms of infection — how to tell your site has been hacked

The trick with redirect viruses is that they are often invisible to the site owner but visible to visitors. You open the admin panel from a bookmark — everything looks normal. A customer arrives from search and lands on a casino. So the first step is learning to recognize the symptoms. Here are the three most common signs.

The site redirects to a casino, pharmacy or ads

The loudest symptom. Open your-site.com and the address bar changes after a second to [mirror-name].invalid or [pharma-domain].invalid. This is a classic casino-redirect or pharma-injection. Advertisers and affiliate networks pay for that traffic, so attackers mass-inject redirects onto other people’s sites — each visitor earns them pennies, but thousands of visitors add up to thousands of dollars a month.

Technically the redirect works either through an injection in .htaccess or a JavaScript snippet in the theme’s header.php or in one of the database tables. Sometimes both methods are used at once for reliability, so you clean one and miss the other.

Pop-ups and banners you never added are appearing

Windows offering “play now,” pharmacy banners, betting or casino ads appear — none of which you ever placed. Sometimes it’s just new links in the footer or hidden blocks with display: none containing text like “buy viagra.” The hidden blocks are invisible to people but visible to search engines: the attacker is promoting their own keywords through your authoritative domain.

Google shows spam pages in Japanese or Chinese

Run a Google search for site:your-site.com and discover hundreds of pages full of hieroglyphs. This is a Japanese keyword hack or Chinese SEO spam. The attacker uses a backdoor to create thousands of spam-content pages and waits for the search engines to index them. Goals vary: selling counterfeit goods, link spam, phishing.

These pages often carry 301 redirects to Asian affiliate offers. Dorking (searching by signatures) surfaces such sites in results — your domain first loses rankings for real queries and then ends up on the Google Safe Browsing blacklist.

Is your site already redirecting visitors?

Every hour of downtime means lost customers and SEO rankings. Hacked site cleanup is $249 flat, completed within 24 hours, with a 60-day guarantee. Free 10-minute check if you’re not sure the site is hacked.

Order cleanup

Who sees the redirect and who doesn’t — the hacker’s logic

The most common reason site owners don’t notice an infection for a long time is that the attackers are smarter than they seem. They don’t redirect everyone — that would be spotted in the first hour. They target: the malware only shows to certain visitors. Here are four typical rules I see in the code.

Redirect only from search (HTTP_REFERER check)

The most frequent variant. The code checks: if the visitor came from google.com — redirect. If they opened the site directly (bookmark or typed the URL) — no redirect. The logic is simple: search traffic brings random visitors; the owner usually arrives via bookmark.

In .htaccess it looks roughly like this:

RewriteCond %{HTTP_REFERER} (google|bing) [NC]
RewriteRule ^(.*)$ [malware-address] [R=301,L]

In JavaScript the check uses document.referrer:

if (document.referrer.match(/google|bing/i)) {
    window.location = '[malware-address]';
}

Redirect only mobile visitors (User-Agent check)

Owners usually work from a desktop; visitors are mostly on mobile. The attacker checks the User-Agent: mobile → redirect, desktop → no redirect. This also helps the infection stay hidden longer.

RewriteCond %{HTTP_USER_AGENT} (android|iphone|ipad|mobile) [NC]
RewriteRule ^(.*)$ [malware-address] [R=302,L]

Redirect only once per session (cookie or IP)

A more advanced variant: the malware sets a cookie or remembers the IP and redirects the same visitor only once. When you check, the site looks normal. An hour later you try in incognito — the redirect appears again because there’s no cookie.

This makes diagnosis much harder and often leads to the conclusion “everything’s fine, the clients are lying.” The clients aren’t lying — each of them sees the redirect exactly once and never again.

How to reproduce it: open the site in incognito from search results

The most reliable way to trigger the redirect:

  1. Open incognito mode in your browser (Ctrl+Shift+N)
  2. Go to Google
  3. Search for your site by brand or the keyword it ranks for
  4. Click the result in the search results (don’t type the URL manually)
  5. Repeat the same steps on a mobile phone

If the redirect fires, you’re now seeing the problem exactly as your clients do. If it doesn’t, try again via VPN with a different IP, after an hour (the malware may wait), or from another device.

Quick 5-minute diagnosis

Before diving into the code, two external tools can confirm the infection in a couple of minutes and point you to where to look. Useful even before cleanup so you understand the scale and have a baseline.

Sucuri SiteCheck — external scan

The service sitecheck.sucuri.net is a free external check. Enter the URL and within a minute you get a report: what infection signs were found, in which files, and whether the site appears on blacklists including Google Safe Browsing. Great for initial diagnosis and as proof for a client: “here’s a public service showing the problem.”

VirusTotal — scan with 70+ engines

On virustotal.com, paste your domain in the URL section. The system runs it through 70+ antivirus engines and checks dozens of blacklists. If the domain is flagged, you’ll see it immediately. Bonus: VirusTotal keeps a history of scans, so you can easily compare “before/after” once the site is cleaned.

Page source — look for iframe and document.write

Open the site in incognito, press Ctrl+U (View Source). Use Ctrl+F and search for suspicious patterns:

  • <iframe — especially with display:none, width="0", height="0" or position:absolute;left:-9999px
  • document.write — almost always malicious; legitimate code in 2026 does not use it
  • Long strings of x, u, base64 — this is obfuscated JavaScript
  • Scripts pointing to third-party domains you never added
  • Hidden blocks style="display:none" with links to casinos or pharma

Every match is evidence. Save the line containing the malicious code — you’ll need it when searching the server with grep.

Where the malicious code hides — 6 common locations

This is where the main technical part begins. An attacker can hide the redirect in dozens of places, but in most cases I see, it’s one of these six typical spots. I walk through each one with examples of infected code.

.htaccess — RewriteRule pointing to a casino

The most popular place for a redirect. The .htaccess file in the site root is processed by Apache before PHP even starts, so the redirect works on every page, including static files. A clean WordPress .htaccess looks like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

An infected version looks like this — notice the extra RewriteCond before the standard rules:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} (google|yandex|bing|mail) [NC]
RewriteCond %{HTTP_USER_AGENT} !(googlebot|yandex|bingbot) [NC]
RewriteRule ^(.*)$ [malware-address] [R=302,L]

# BEGIN WordPress
...

Also check .htaccess files in subfolders — attackers often hide a second copy there. If you cleaned the main .htaccess but the redirect still happens, look in wp-content/, wp-content/uploads/, and the theme root.

index.php, wp-load.php, wp-config.php — injection at the top of the file

If the redirect only affects dynamic pages and not every URL, the injection is probably in the WordPress PHP files. The most common targets are index.php in the root, wp-load.php, and wp-config.php. A typical sign is a block of suspicious code right at the beginning of the file, before the opening <?php or immediately after it:

<?php
$qV="b"."as"."e6"."4_"."de"."co"."de";
@eval($qV("[base64-payload-removed]"));
?>
<?php
/**
 * Front to the WordPress application...

The long base64 string decodes into PHP code that performs the redirect. The $qV = "b"."as"."e6"."4_"."de"."co"."de" construction builds the base64_decode string from pieces to evade a simple grep for base64_decode.

Theme functions.php and header.php — JavaScript injection

If the redirect happens on the browser side (visible in DevTools → Network), check the theme template. The injection is most often in header.php:

<?php wp_head(); ?>
<script type="text/javascript">
eval(atob('[base64-payload-removed]'));
</script>
</head>

Or a PHP snippet in functions.php that adds the redirect via a hook:

add_action('wp_head', function() {
    if (preg_match('/google|yandex/', $_SERVER['HTTP_REFERER'] ?? '')) {
        echo '<script>window.location="[malware-address]"</script>';
    }
});

wp-content/uploads — PHP shells disguised as images

Attackers like to hide backdoors in the wp-content/uploads/ folder because WordPress writes uploaded files there and site owners rarely check it. Any .php file inside uploads/ is a 100% sign of infection — WordPress never places PHP files there itself.

Common shell names: thumb.php, cache.php, logo.php, image.php, upload.php. Sometimes they use double extensions like .jpg.php or .png.php. Find them all via SSH:

find wp-content/uploads -type f \( -name "*.php" -o -name "*.phtml" -o -name "*.php5" -o -name "*.php7" \)

Delete every file you find. They usually contain a full web shell (c99shell, FilesMan, WSO) with an interface for controlling the server.

wp_options and wp_posts tables — URL replacement and content injection

If you found nothing in the files but the redirect remains, look in the database. The most common infection points are:

wp_options — the siteurl and home fields must contain your real URL. If they show something like https://malicious.example, the redirect is being done through WordPress. Check with SQL:

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

-- Suspicious values containing injections
SELECT option_name, option_value FROM wp_options
WHERE option_value LIKE '%base64%' OR option_value LIKE '%eval%' OR option_value LIKE '%<script%';

wp_posts — attackers sometimes inject hidden links or scripts into post content:

SELECT ID, post_title FROM wp_posts
WHERE post_content LIKE '%<iframe%' OR post_content LIKE '%display:none%' OR post_content LIKE '%base64_decode%';

Cron jobs — the virus recreates itself on a schedule

The most insidious mechanism. The attacker registers a WP-Cron task or a system cron job that restores deleted shells every hour. You clean uploads/ in the morning and they’re back by lunch.

Check WP-Cron with WP-CLI:

wp cron event list

Remove any suspicious tasks with unclear names (such as wp_check_referrals or wp_dynamic_load). Also check the system cron on the server:

crontab -l

Any entry containing wget, curl, php -r, or a URL is definitely malicious.

What Malicious Code Looks Like — Examples

In the previous section I showed clean and infected .htaccess. Here are three more typical patterns — specific examples that I regularly see on real client sites.

eval(base64_decode(…)) — classic PHP inject

The most common construction. Attackers pack the malicious code in base64 (or multiple layers of base64+gzinflate+str_rot13 to make it harder to read) and run it with a single eval() line:

<?php
@eval(base64_decode('[base64-payload-removed]'));

Decoding the base64 gives:

⚠ Decoded payload executes arbitrary PHP code passed through an HTTP parameter. I’m not showing the exact form — it’s a working one-line backdoor.

This is a backdoor: the attacker can run any PHP code through the GET parameter ?cmd=.... You can decode it manually with any online base64 decoder or PHP CLI:

php -r "echo base64_decode('[base64-payload-removed]');"

JavaScript inject: document.write and hidden iframe

On the browser side, a popular technique is a hidden iframe with display:none. You won’t see it on the page, but it loads content from a foreign domain and can trigger redirects:

<iframe src="[malware-address]"
        width="0" height="0" frameborder="0"
        style="display:none;visibility:hidden;position:absolute;left:-9999px">
</iframe>

Or through document.write with an obfuscated URL:

<script>
var s = String.fromCharCode(/* character codes for the start of the <script src= tag */);
document.write(s + '"[malware-address]"></script>');
</script>

String.fromCharCode builds the <script src= string from ASCII codes — a simple grep for <script src= won’t catch it.

Replacing siteurl/home in wp_options

The quietest attack changes the siteurl and home fields in the database to a foreign domain. WordPress then redirects every request there. You open the site and get sent to malicious.example because WordPress itself thinks the site has moved.

Check and quick fix through phpMyAdmin or WP-CLI:

# through WP-CLI (if the admin area is still available)
wp option get siteurl
wp option get home

# if the values have been changed
wp option update siteurl 'https://your-real-site.com'
wp option update home 'https://your-real-site.com'

Or directly in SQL:

UPDATE wp_options SET option_value = 'https://your-real-site.com'
WHERE option_name IN ('siteurl', 'home');

Step-by-step cleanup — how to remove the redirect and the virus

Now that you know where to look, let’s go through the steps. I follow this checklist — skipping any step almost guarantees reinfection in a few days.

Step 1 — back up the infected site (for analysis)

Before making any changes, create a full backup of the files and database. The infected version, exactly as it is now. This matters because attackers sometimes leave complex traps, and you can only understand what they did from a live copy. Via SSH:

cd ~/public_html
tar -czf ~/site-infected-$(date +%Y%m%d).tar.gz .
mysqldump -u DB_USER -p DB_NAME > ~/db-infected-$(date +%Y%m%d).sql

Save both files locally. If anything goes wrong during cleanup, you have a rollback point.

Step 2 — clean .htaccess

Open .htaccess in the site root. Remove everything that is not part of the standard WordPress block (between # BEGIN WordPress and # END WordPress). If the standard block is missing, replace the contents with a clean template:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Check .htaccess in all subfolders:

find . -name ".htaccess" -type f

WordPress logic means there should be no .htaccess file in wp-content/, wp-content/uploads/, or wp-content/plugins/ — delete any you find.

Step 3 — compare the WordPress core with the original

Download a clean copy of your WordPress from wordpress.org and compare the core. The simplest approach is to replace the entire wp-admin/, wp-includes/, and root PHP files (except wp-config.php and .htaccess) with fresh ones.

Alternative via WP-CLI:

wp core verify-checksums

The command lists every core file that differs from the original. Each one is a candidate for restoration from a clean copy.

Step 4 — search for shells and backdoors with grep

Run a search across the entire site for common malicious signatures:

cd ~/public_html
grep -rE "eval\s*\(\s*base64_decode" --include="*.php" .
grep -rE "@assert\s*\(" --include="*.php" .
grep -rE "create_function\s*\(" --include="*.php" .
grep -rE "preg_replace.*/.*/e" --include="*.php" .
grep -rE "FilesMan|WSO|c99shell|b374k" --include="*.php" .

Inspect every file in the output manually. If the file belongs to a standard plugin or the core and contains suspicious code, reinstall it from a clean source. If you do not recognize the file (especially in uploads/), delete it.

Step 5 — clean the database

Check three tables via phpMyAdmin or WP-CLI:

-- siteurl and home must point to your domain
SELECT option_name, option_value FROM wp_options
WHERE option_name IN ('siteurl', 'home');

-- Hidden admins
SELECT u.ID, u.user_login, u.user_email
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%';

-- Spam injections in posts
SELECT ID, post_title FROM wp_posts
WHERE post_content LIKE '%<iframe%'
   OR post_content LIKE '%base64%'
   OR post_content LIKE '%display:none%';

Remove or restore suspicious options to the correct value. Delete hidden admins via Users → All Users in the admin panel (transferring content to your account). Clean spam injections in posts manually if there are only a few, or run an SQL UPDATE with REPLACE for bulk cleanup.

Step 6 — change passwords and update keys

After removing the malicious code, change all passwords in this order:

  1. Hosting account
  2. FTP / SSH
  3. Database (create a new MySQL user, update wp-config.php, delete the old user)
  4. All WordPress admins

In wp-config.php, update the salts and authentication keys (AUTH_KEY and so on) — generate fresh ones at api.wordpress.org/secret-key/1.1/salt/ and replace the block. This invalidates all active sessions, so any attacker who had a session loses access.

Went through the steps and still can’t find the source?

Backdoors can hide in dozens of places and return through cron jobs. I’ll perform a deep cleanup, find the entry point, and close it. $249 flat, 60-day guarantee.

Order deep cleanup

How the virus got on the site — causes

Cleaned it up — great. But if you don’t close the entry point, the virus will return in a week. I analyzed the four most common reasons for WordPress site compromises.

Vulnerable plugin or theme (the most common cause)

The most common cause. You’re running a plugin at version 2.3, the developer fixed an RCE vulnerability in 2.4, but you never installed the update. Attackers use automated scanners (Shodan, WPScan) to find sites with vulnerable versions and exploit them.

The WordPress vulnerability database is at wpvulndb.com and wordfence.com/threat-intel. After cleanup, check every installed plugin for open CVEs. If a plugin is no longer maintained by its developer, remove it — it’s a ticking time bomb.

Nulled theme or pirated plugin with a built-in backdoor

Downloaded a paid plugin “for free” from a torrent or warez site? There’s a good chance it contains a built-in backdoor — sometimes the code stays hidden for years. Attackers maintain lists of every site using nulled builds and can activate the backdoor at any time.

The fix is to remove all nulled plugins and themes and replace them with licensed or free alternatives from the official repository. Saving on a license is not worth the risk of losing the entire site and your reputation.

Weak password and brute-force attacks on wp-login.php

If the admin password is something like admin123 or qwerty2024, an attacker can guess it through brute force. Attacks target /wp-login.php and /xmlrpc.php from thousands of IPs at once. A sign in the server logs is a flood of POST requests:

tail -10000 access.log | grep "POST /wp-login.php" | wc -l

If the number is high (hundreds or thousands per hour), you’re under active brute-force attack. Protection: use 16-character passwords from a password manager, limit login attempts (Limit Login Attempts, Wordfence), and enable two-factor authentication for all admins.

Infection from a neighbor on shared hosting

On shared hosting you share one server user account with dozens of sites. If a neighbor’s site was compromised and the attacker gained write access, they can reach your files too — especially if file permissions are too open (777 instead of 644).

You have two options: fix the permissions (644 for files, 755 for folders, 600 for wp-config.php) or move to a VPS with isolated resources. If your host has already suspended the account after the hack, moving to a new server is often faster than waiting for reinstatement.

Protection after cleanup — preventing a repeat

Cleanup without protection only treats the symptoms. If you don’t close the hole the attacker used, the same thing will happen again within a month. Here are four basic measures I put in place for every client after cleanup.

Two-factor authentication and restricted access to /wp-admin/

Enable 2FA for all administrators with WP 2FA, Two-Factor (from the WordPress team), or Wordfence Login Security. Even if the password is stolen, no one can log in without the TOTP code.

WAF (Wordfence or Sucuri) and regular scanning

A Web Application Firewall filters traffic before it reaches WordPress. Wordfence provides a free application-level WAF; Sucuri offers a premium network-level WAF. Cloudflare Pro includes WAF even on the free plan.

Turn on daily scanning — Wordfence or Sucuri compare files against a clean baseline and alert you to changes. Early detection is half the battle.

CMS and plugin updates + file permission audit

Enable automatic updates for minor core and plugin releases. Major versions (5.x → 6.x) are better installed manually after testing — they can contain breaking changes.

Check file permissions — they are often changed during an attack:

find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
chmod 600 wp-config.php

After cleanup the site may run slower (caches were cleared) — speed optimization will restore performance.

Regular backups stored separately

Backups must not live on the same server as the site. If the server is compromised, the backups are too. Use cloud storage: Google Drive, Dropbox. Plugins like UpdraftPlus and Solid Security work with these services.

At minimum, run daily backups with 30-day retention. That’s enough to roll back even if the infection happened three weeks ago.

Cleanup is a one-time fix. But who will keep watch afterward?

Without ongoing support, a cleaned site often gets hacked again — the same hole gets exploited. I offer monthly maintenance from $99/month: automatic backups, updates, security monitoring, and quick response.

Get maintenance

Frequently Asked Questions

Spam pages remain in the search index even though they are gone from the site. Remove the URLs in Google Search Console (Index → Removals). Update sitemap.xml to exclude all nonexistent pages. Submit a recrawl request. Reindexing and cleanup usually takes 3–14 days.
A simple redirect in .htaccess can be removed yourself — just delete the foreign lines from the file. But if the infection runs deeper (shells in uploads, database injects, cron jobs that recreate the virus), contact a specialist. Incomplete cleanup almost guarantees reinfection within days. Sign you need a pro: you cleaned the visible spots and the symptoms returned the next day.
First clean the site completely — every file and the database. Then submit a review request in Google Search Console (Security Issues → Request Review). In the request describe what was found and how it was cleaned. Google usually reviews within a few days. Until then visitors see the warning and traffic drops.