Site Redirecting to Spam? How to Stop Unwanted Redirects
When people click your site in Google and land on a prize scam, a gambling page or a fake virus warning, something has added a redirect you did not set up. It is usually malicious code in your .htaccess file, injected JavaScript, a compromised plugin or a bad third-party script, and it is often written so that you, the owner, never see it. Unwanted redirects lose you customers, can bring browser warnings and Search Console security alerts, and usually mean an attacker still has a way in. This guide shows you how to reproduce a hidden redirect, find the code causing it at each layer, remove it properly rather than just the visible part, and lock the site down so it does not come back.
- What an unwanted redirect is, and why it happens
- Why you cannot always see the redirect yourself
- Common causes of unwanted redirects
- How to find the malicious code
- Removing the redirect properly
- Platform notes
- A worked example
- The fix, step by step
- Edge cases worth knowing
- Keeping redirects under control
- Questions and answers
What an unwanted redirect is, and why it happens
A redirect is an instruction that sends a browser from one address to another. Most redirects on a site are deliberate and useful: http to https, a non-www address to www, or an old page to its replacement. An unwanted redirect is one you did not set up, where visitors who click your link in Google or open your home page end up on a gambling site, a fake prize page, a scam shop or a page telling them their phone has a virus.
When a site redirects to spam, the cause is almost always one of three things: code added to the site after an attacker got in, a third-party script the site loads that has turned bad, or a change to settings outside the site such as DNS or a CDN rule. Each one works at a different layer, so each needs a different search.
| Layer | How the redirect is done | Where to look |
|---|---|---|
| Web server | Rewrite rules that send a 301 or 302 before any page is built | .htaccess, nginx configs, Plesk or cPanel redirect settings |
| Application | PHP or other server code that sends a Location header | Theme files, plugins, must-use plugins, wp-config.php, index.php |
| Database | Scripts stored in posts, widgets or settings, or a changed site address | wp_options, wp_posts, page builder data |
| Browser script | JavaScript that changes window.location after the page loads | Injected script tags, compromised ad or analytics scripts |
| Outside the server | DNS pointing elsewhere, or a redirect rule in a CDN account | Domain registrar, Cloudflare Redirect Rules and Page Rules |
The damage goes beyond annoyed visitors. Google can flag the site in Search Console under Security issues, Chrome can show a red warning screen, and search traffic can drop sharply. The attacker also usually still has access, so the redirect returns if you only remove what you can see.
Why you cannot always see the redirect yourself
Site owners often say the redirect only happens to other people. That is by design. Malicious redirects are usually conditional, so the person most likely to notice them, the logged-in owner on a desktop computer, never sees them. Common conditions are:
- Only from search results. The rule checks the referrer and only fires when the visitor comes from Google, Bing or another search engine. Typing the address directly shows the normal site.
- Only on mobile. The rule checks the user agent and only redirects phones, because many owners check their site on a computer.
- Only once. A cookie is set on the first visit, and repeat visitors are left alone, so the owner who reloads to check sees nothing.
- Not for logged-in users. Injected WordPress code skips anyone with a login cookie.
- Only some of the time, or only in some countries. Random or location-based rules make the problem look intermittent.
You can reproduce most of these with curl, which never stores cookies unless asked and lets you pretend to be a phone arriving from Google:
# Show every hop, as a phone arriving from a Google search
curl -sIL \
-A "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1" \
-e "https://www.google.com/" \
https://www.example.com/ | grep -iE "^HTTP|^location"If this shows a Location header pointing to a domain you do not recognise, the redirect is server-side. If curl shows a normal 200 but phones still get redirected, the redirect is done by JavaScript in the browser, so look at the page source and the scripts it loads.
Common causes of unwanted redirects
These are the causes found most often when a small business site starts sending visitors elsewhere, roughly in order of how often they turn up.
| Cause | What it looks like | How common |
|---|---|---|
Malicious .htaccess rules | RewriteCond lines checking the referrer or user agent, then a RewriteRule to an unknown domain | Very common on Apache and LiteSpeed hosting |
| Injected JavaScript | Script tags with odd domains, or code using eval, atob or String.fromCharCode to hide itself | Very common, often in posts, widgets or theme headers |
| Compromised or fake plugin | A plugin you did not install, or a nulled premium plugin with a backdoor | Common on WordPress |
| Changed site address | siteurl or home in wp_options set to another domain | Occasional, causes every page to redirect |
| Bad ad or third-party script | Redirects only on pages carrying ads or a specific widget | Occasional, often called malvertising |
| Hijacked DNS or CDN | The whole domain points somewhere else, or a Redirect Rule you did not create | Rare, but serious |
A legitimate redirect set up wrongly can also feel unwanted, for example a loop between http and https, or every old URL sent to the home page. Those are covered in fixing redirect loops and fixing HTTPS redirects.
How to find the malicious code
Take a full backup of files and database before you change anything, even though they are infected. You may need them to compare later. Then search, starting with the most common places.
Web server rules
# Every .htaccess file under the site, with any redirect lines
find /var/www/example.com -name ".htaccess" -exec grep -HniE "RewriteCond|RewriteRule|Redirect" {} \;A normal WordPress .htaccess has a short block between # BEGIN WordPress and # END WordPress. Anything checking HTTP_REFERER or HTTP_USER_AGENT for search engines or phones, and sending visitors to an outside domain, is malicious. Check every folder, including wp-content/uploads, because attackers hide copies there.
Recently changed and suspicious files
# PHP files changed in the last 14 days
find /var/www/example.com -name "*.php" -mtime -14 -printf "%TY-%Tm-%Td %p\n" | sort
# Common obfuscation patterns
grep -RlE "eval\(base64_decode|eval\(gzinflate|str_rot13|fromCharCode|atob\(" /var/www/example.com --include=*.php --include=*.js
# PHP files in uploads, which should only hold media
find /var/www/example.com/wp-content/uploads -name "*.php"WordPress core, plugins and database
WP-CLI can compare core and plugin files with the official copies and search the database directly:
wp core verify-checksums
wp plugin verify-checksums --all
wp option get siteurl
wp option get home
wp db search "<script" --all-tables --stats
wp user list --role=administratorAny file the checksum command reports as changed or unexpected deserves a look. Admin users you do not recognise are a sign the attacker kept a way back in.
The browser side
Open the affected page in a private window in Chrome with DevTools open on the Network tab and Preserve log ticked, then load it with phone emulation on. The request just before the jump to the spam domain shows which script or response triggered it. View the page source and look for script tags pointing at domains you do not use. The security audit guide explains how to review third-party scripts across a site.
Removing the redirect properly
Removing the visible redirect is only half the job. If the way in stays open, the code comes back within days. Clean in this order:
- Replace, do not edit, core and plugin files. Reinstall WordPress core, then reinstall every plugin and theme from the official source. With WP-CLI:
wp core download --force --skip-contentandwp plugin install plugin-name --forcefor each one. - Clean the rules. Restore a clean
.htaccessand delete any extra ones in uploads and other content folders. - Clean the database. Remove injected scripts from posts, widgets and options, and correct
siteurlandhome. - Close the door. Delete unknown admin users, remove nulled plugins, and update everything.
- Change every secret. Hosting, SFTP, database, WordPress and registrar passwords, and new WordPress salts.
A clean WordPress .htaccess on Apache 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 WordPressAnd this is the kind of rule you are looking for and should delete, here sending mobile visitors from search engines away:
RewriteCond %{HTTP_REFERER} (google|bing|yahoo) [NC]
RewriteCond %{HTTP_USER_AGENT} (android|iphone|mobile) [NC]
RewriteRule ^(.*)$ https://spam-destination.example/? [R=302,L]To reset the salts and stop any stolen login cookies working, run wp config shuffle-salts. Everyone, including you, will need to log in again.
Platform notes
- WordPress. Also check
wp-content/mu-plugins, which loads automatically and does not show in the normal plugin list, and the scheduled tasks withwp cron event list. See redirects in WordPress for the legitimate redirect settings you should keep. - nginx. nginx ignores
.htaccess, so check/etc/nginx/sites-enabled/and included files forreturn 301orrewritelines you did not add, usingsudo nginx -T | grep -nE "return 30|rewrite". - Plesk and cPanel. Check the domain's hosting settings and any additional nginx or Apache directives box, and the server's cron jobs with
crontab -lfor each system user. - Cloudflare. Look at Rules, then Redirect Rules and Page Rules, for anything you did not create, and review the account's members and API tokens. See redirects in Cloudflare.
- Shopify and hosted builders. Server files are not yours to edit, so the usual causes are a third-party app or a script pasted into the theme. Remove recently added apps and check the theme code for unfamiliar script tags.
A worked example
The owner of Example Bakery hears from a customer that clicking the site in Google on her phone opened a page saying she had won a phone. On his laptop the site looks normal.
Running the curl test as an iPhone with a Google referrer shows a 302 to an unknown domain, so the redirect is on the server. A search of .htaccess files finds the WordPress one clean, but a second file in wp-content/uploads/2026/08/ holds three RewriteCond lines like the example above. That alone would not affect the home page, so he keeps looking. The checksum command reports that wp-includes/load.php has been modified, and a search finds a PHP file called wp-cache-helper.php in mu-plugins that he never installed. It contains a long base64 string run through eval, which sends the same redirect header.
He reinstalls core, deletes the must-use plugin and the extra .htaccess, finds an unknown administrator called wpsupport2 and removes it, then updates an out-of-date form plugin that had a known vulnerability. He changes all passwords and shuffles the salts. The curl test now returns 200, and a week later, with no changes reappearing in the file search, he requests a review in Search Console.
The fix, step by step
Step 1
Reproduce the redirect
Run the curl test with a phone user agent and a Google referrer, using -sIL so every hop is shown, and look for a Location header to a domain you do not own. Repeat in a private browser window on a real phone, arriving from a Google search for your business name. Write down which conditions trigger it. A server-side redirect shows in curl; a JavaScript redirect only shows in the browser, which tells you where to search next.
Step 2
Back up and secure access
Take a full copy of the site files and database as they are now, and store it off the server. Then change the hosting, SFTP and database passwords, and turn on two-factor sign-in for the hosting panel, the domain registrar and any CDN account. This stops the attacker using stolen credentials while you clean. Confirm you can still log in to everything with the new passwords before you move on.
Step 3
Check server rules
Search every .htaccess file under the site for RewriteCond and RewriteRule lines, and on nginx run sudo nginx -T and look for return and rewrite lines you did not add. Delete any rule that checks the referrer or user agent for search engines or phones and sends visitors to an outside domain. Remove extra .htaccess files from upload folders. Rerun the curl test to see whether the redirect has changed.
Step 4
Find injected code in files
List PHP files changed in the last two weeks with find -mtime -14, and search for hiding patterns such as eval(base64_decode, gzinflate and fromCharCode. Check wp-content/mu-plugins and look for PHP files inside wp-content/uploads. On WordPress, run wp core verify-checksums and wp plugin verify-checksums --all to see which files differ from the official copies. Note every file found, with its path and date, before removing anything, so you can work out how the attacker got in.
Step 5
Reinstall core, plugins and themes
Rather than editing infected files, replace them. Run wp core download --force --skip-content to reinstall WordPress core, then reinstall each plugin and theme from the official directory or the vendor. Delete any plugin you did not install or no longer use, and every nulled plugin. Run the checksum commands again; they should report that all files match. Keep your own uploads, but remove anything in them that is not media.
Step 6
Clean the database
Check wp option get siteurl and wp option get home and correct them if they point elsewhere. Search the database for <script and for unknown domains with wp db search, then remove injected code from posts, widgets and options, checking each match by hand so you do not delete your own analytics. List administrators with wp user list --role=administrator and delete any account you do not recognise. Then run wp config shuffle-salts.
Step 7
Check scripts and outside settings
Open the page in Chrome DevTools with Preserve log ticked and phone emulation on, and check no request now leads to the spam domain. Review every third-party script tag and remove any you cannot explain. Look at your DNS records at the registrar and at Cloudflare Redirect Rules and Page Rules for changes you did not make. Purge the page cache and the CDN cache so visitors get the cleaned pages.
Step 8
Update, verify and request review
Update every remaining plugin, theme and the PHP version, then repeat the curl test from several conditions and confirm each returns your own page with a 200. Check the Security issues and Manual actions reports in Search Console. If either lists a problem, fix it and use Request review, explaining what you removed. Keep watching the file and checksum results for a few weeks to make sure nothing comes back.
Edge cases worth knowing
- Caches hide the fix. A page cache, CDN cache or the visitor's browser can keep serving the old redirect after you clean the server. Purge every cache layer after cleaning.
- Permanent redirects are cached by browsers. If the attacker used a
301, some visitors' browsers remember it. Clearing that browser's history for your site fixes it for them. - Ads can redirect without a hack. If the redirect only happens on pages with ads, a bad advert in the network is the likely cause. Report it to the ad provider and check whether the problem follows a single ad slot.
- Content Security Policy helps. A strict policy limits which domains scripts can load from, which blocks many injected scripts. Start in report-only mode as described in CSP report-only.
- Search Console warnings take time to clear. After fixing a security issue, use Request review in the Security issues report and describe what you fixed. Google reviews these, and the warning stays until the review passes.
Keeping redirects under control
- Keep WordPress core, plugins and themes updated, and remove any you do not use. Never install nulled premium plugins.
- Turn on two-factor sign-in for hosting, WordPress admin, the domain registrar and Cloudflare.
- Run
wp core verify-checksumsandwp plugin verify-checksums --allon a schedule and alert on any change. - Repeat the curl test as a phone from Google once a week, or set up monitoring that does it for you.
- Keep dated off-site backups, so you can restore to a clean point if needed.
- Add security headers, including a Content Security Policy, to reduce what injected code can do.
1. Why is my website redirecting to a spam site?
Your website is most likely redirecting to spam because it has been hacked and malicious code has been added to its files, database or server rules. The most common places are .htaccess rewrite rules, injected JavaScript in posts or theme files, and fake or compromised plugins. Less often, a third-party ad or widget script has turned bad, or someone has changed your DNS or CDN settings. The redirect is usually conditional, so it may only affect mobile visitors arriving from search results.
2. How do I stop unwanted redirects on my site?
Stop them by finding and removing the code that causes them, then closing the hole the attacker used so it cannot be added again. Check every .htaccess file and server config for rules you did not write, reinstall WordPress core, plugins and themes from official sources, clean injected scripts from the database, and delete unknown admin users. Then change every password, reset the WordPress salts, update everything and purge your caches so visitors get the clean version.
3. Why does the redirect not happen when I visit my own site?
Malicious redirects are usually built to avoid the site owner, so they often only fire for visitors arriving from search engines, for mobile devices, for people who are not logged in, or only on the first visit. If you type the address directly on a desktop while logged in, you may never see it. Test with curl using a phone user agent and a Google referrer, or search for your site on a phone in a private window, to see what customers see.
4. What causes redirects in a browser?
Redirects in a browser are caused either by the website sending a redirect instruction or by something on your own device. A site can send a 301 or 302 response from the server, or run JavaScript that changes the page address. On your device, unwanted browser extensions, adware and changed browser settings can redirect searches and pages on every site you visit. If it happens on many unrelated sites, the problem is your browser; if only on one site, it is that site.
5. How do I prevent automatic redirects in my browser?
Remove extensions you do not recognise, reset your browser settings and keep the browser updated, because unwanted redirects across many sites usually come from adware or a rogue extension. In Chrome, open the extensions page and remove anything unfamiliar, then use the reset settings option. Run your operating system's security scan as well. Pop-up and redirect blocking is on by default in modern browsers, so if redirects continue after a reset, check the device for unwanted programs.
6. Can unwanted redirects get my site removed from Google?
They can cause Google to flag your site as hacked or deceptive, which adds warnings in search results and in Chrome, and sneaky redirects can lead to a manual action that removes pages from results. Traffic often drops sharply while the warning is in place. Once you have cleaned the site, check the Security issues and Manual actions reports in Search Console, fix everything listed and use Request review. The warnings are removed after Google confirms the site is clean.
7. Will a security plugin remove malicious redirects?
A security plugin can help find malicious redirects, but it may not remove every part of the infection on its own. Scanners are good at spotting known patterns and changed core files, yet attackers often hide code in the database, in upload folders, in must-use plugins or in server rules the plugin cannot see. Use a scanner as one tool, then check .htaccess files, the database and admin users yourself, and reinstall core and plugins from clean copies.
Our security audit and redirect checker request your pages the way visitors and crawlers do and show every hop, so a redirect to a domain you do not own stands out straight away.
Open Security Audit Fixes โ