The short answer
A WordPress site redirects to spam when malicious code or a compromised plugin/theme injects unwanted URLs into pages. Check core files, plugins, themes and server configs, clean the infection, and harden the environment to stop future redirects.
Why spam redirects matter for WordPress sites
Spam redirects can severely damage a WordPress site's search‑engine visibility. When crawlers encounter unexpected outbound links, search engines may flag the site as compromised, drop rankings, or even remove it from indexes. This loss of organic traffic directly reduces potential customers and revenue, making recovery costly and time‑consuming. Moreover, the presence of malicious links signals poor site hygiene, which can deter legitimate visitors and partners from trusting the brand.
Beyond SEO, spam redirects erode a site's reputation and expose users to further threats. Visitors who are sent to phishing or malware‑laden pages may experience data theft, leading to complaints and loss of confidence. Search engines and security services may label the domain as unsafe, triggering browser warnings that discourage access. Over time, this can increase support tickets, damage client relationships, and open the door to additional attacks such as credential stuffing or ransomware.
- Reduced search‑engine rankings and traffic
- Browser warnings that block access for users
- Potential loss of customer trust and brand credibility
- Increased support workload handling security complaints
- Higher risk of subsequent malware infections
After checking logs and site files, look for unexpected outbound URLs, modified .htaccess rules, or unknown plugins that could be injecting the redirects.
Initial signs and quick verification
When a visitor reports being sent to an unwanted site, the first step is to verify the behavior yourself. Open the affected URL in at least two different browsers such as Chrome and Firefox. Use each browser's private or incognito mode to bypass cached content and stored cookies. If the redirect occurs in both regular and private windows, it is likely not a local browser extension issue. Take note of the exact URL you typed and the final destination shown after the redirect.
Next, confirm the redirect from the command line to eliminate any client‑side factors. Run a simple curl request to the page and observe the HTTP response headers. Use the -I flag to fetch only headers and the -L flag to follow redirects. Compare the output from your server's IP and from an external network if possible. Consistent redirection across browsers and curl indicates that the site itself is serving the unwanted location.
- Test in multiple browsers (e.g., Chrome, Firefox).
- Use incognito/private mode to avoid cached data.
- Check the URL before and after the redirect.
- Run
curl -I -L <url>to see HTTP headers. - If possible, repeat the curl test from a different network.
curl -I -L https://example.comLook for a Location: header in the curl output that points to an unexpected domain. In the browser, note the address bar after the redirect. If both show the same suspicious target, the site is likely compromised and further investigation is required.
File‑system and database inspection
Start by comparing the current WordPress core files with the official versions. Download the same WordPress release from wordpress.org, extract it to a temporary directory, and use a checksum tool such as sha256sum to compare each file in wp-includes and wp-admin. Any mismatch may indicate a modified core file. Next, review the wp-content directory. Look for unexpected PHP files, especially in plugins and themes folders, and check the timestamps. Plugins and themes should only contain files that belong to the installed package; extra files often hide malicious code.
Inspect the database for injected payloads, focusing on the wp_options table. Query the option_name column for known WordPress settings like siteurl, home, active_plugins, and theme_mods_*. Search the option_value column for suspicious strings such as eval(, base64_decode(, or external URLs. Also scan the posts and postmeta tables for similar patterns, as attackers sometimes embed redirects in content or custom fields. Clean any rogue entries and replace them with the original values.
- Verify core file checksums against official releases
- Search
wp-contentfor unknown PHP files - Query
wp_optionsfor suspiciousevalorbase64_decodestrings - Check timestamps of plugin and theme files
- Review
active_pluginsoption for unexpected entries
# Example: list PHP files in plugins and themes
grep -R "eval(" /var/www/html/wp-content/plugins /var/www/html/wp-content/themes
# Example: search wp_options for base64 strings
mysql -u wpuser -p -e "SELECT option_name,option_value FROM wp_options WHERE option_value LIKE '%base64_%';" wp_databaseThe checksum list should show only matching hashes for core files. Any differences need further investigation. In the database output, look for rows where the value contains code execution functions or external URLs; those are likely injection points to clean.
Cleaning the infection
Start by taking a fresh backup of the site files and the database. Then download a clean copy of the same WordPress version from the official repository. Replace the core files, themes and plugins directories with the clean versions, preserving only the wp-content/uploads folder. Use a file comparison tool to verify that no unexpected PHP files remain in the root or sub‑directories. After the file replacement, scan the database for suspicious entries such as unknown admin users, rogue option_name values, or injected JavaScript in posts, and delete or clean them manually.
Next, reset all passwords that could have been exposed. Change the WordPress admin password, any user accounts with publishing rights, and the database user password. Update the salts in wp-config.php to invalidate existing sessions. Finally, regenerate the .htaccess file using WordPress permalink settings or a default template, and ensure file permissions are set to the recommended values (files 644, directories 755).
- Replace core, theme and plugin files with clean copies
- Search and remove unknown admin users and malicious options in the database
- Reset WordPress, database and FTP/SFTP passwords
- Update security salts in
wp-config.php - Regenerate a clean
.htaccessfile
# Example: download clean WordPress core and extract
wget https://wordpress.org/latest.tar.gz -O /tmp/wordpress.tar.gz
tar -xzf /tmp/wordpress.tar.gz -C /tmp
# Copy clean files over the site (preserve uploads)
rsync -av --exclude='wp-content/uploads' /tmp/wordpress/ /var/www/html/After completing these steps, the site should load without unexpected redirects. Verify that the homepage and a few internal pages open cleanly, and check the source code for any remaining unfamiliar scripts or iframes.
What to avoid when fixing redirects
When you see a WordPress site redirecting visitors to spam, it is tempting to act quickly and delete files that look suspicious. Deleting core WordPress files or plugin directories without confirming their purpose can break the site and make recovery harder. Similarly, turning off security modules such as ModSecurity or the server firewall may stop the immediate symptom but also removes a layer of protection, leaving the site open to further compromise. Always keep a recent backup or snapshot before making any changes, so you can revert if something goes wrong.
Another common mistake is to skip a thorough investigation and jump straight to reinstalling WordPress or the entire server. Skipping backups, logs, and file integrity checks means you may miss hidden backdoors that will re‑appear after the reinstall. Also, avoid making changes directly on a live production environment; use a staging copy or maintenance mode to test fixes. Document each step you take, and verify that the site functions correctly before bringing it back online.
- Do not delete core WordPress files without verification.
- Do not disable ModSecurity, firewalls, or other security modules.
- Never skip creating a backup or snapshot before changes.
- Avoid editing files directly on the live site; use a staging copy.
- Do not ignore server logs and file integrity reports.
grep -R "eval" /var/www/html/wp-content/ | cut -d: -f1 | sort -uAfter running the command, review the listed files for unexpected eval() usage. If any files appear suspicious, compare them with known clean versions or restore them from backup. Confirm that redirects no longer occur before disabling maintenance mode.
Hardening WordPress after cleanup
After you have removed the malicious redirects, tighten WordPress to stop future compromises. Install a reputable security plugin such as Wordfence, Sucuri, or iThemes Security. These tools add a firewall, scan for altered files, and can block brute‑force login attempts. Keep the plugin and its signatures up to date, and enable any automatic blocking features it provides. Regularly review the plugin’s security logs for unusual activity, and schedule scans at least weekly.
Set strict file permissions to limit what the web server can write. Use chmod 644 for most files and chmod 755 for directories, while keeping wp-config.php at chmod 640. Create separate WordPress user accounts with the minimum capabilities needed; avoid using the admin account for daily tasks. Enable two‑factor authentication for all privileged users and enforce strong, unique passwords. Finally, apply WordPress core, theme, and plugin updates as soon as they are released.
- Install a well‑known security plugin and keep it updated.
- Set file permissions: 644 for files, 755 for directories, 640 for
wp-config.php. - Create least‑privilege user accounts; use admin only for essential tasks.
- Enable two‑factor authentication for all privileged users.
- Schedule automatic core, theme, and plugin updates.
# Example commands – read before executing
# Set secure permissions
find /var/www/html -type f -exec chmod 644 {} \;
find /var/www/html -type d -exec chmod 755 {} \;
chmod 640 /var/www/html/wp-config.php
# Install a security plugin via WP‑CLI (replace with your chosen plugin)
wp plugin install wordfence --activateAfter applying these steps, the site should show no permission errors in the web server log, and the security plugin dashboard should report a clean status. Verify that only intended users can log in and that two‑factor prompts appear for privileged accounts.
Ongoing monitoring and maintenance
Enable WordPress debug logging and system audit logs to capture any unexpected redirects. Add define('WP_DEBUG', true); define('WP_DEBUG_LOG', true); to wp-config.php so PHP errors and warnings are written to wp-content/debug.log. On the server, configure rsyslog or journald to retain Apache/Nginx access logs for at least 30 days. Regularly review these logs for requests to wp-admin/admin-ajax.php or unknown query strings that trigger Location: headers. Early detection reduces the window an attacker can exploit a compromised file or plugin.
Schedule automated scans with a reputable tool such as clamav for malware and wordpress-cli for core, theme, and plugin integrity checks. Use crontab to run wp core verify-checksums and wp plugin verify-checksums daily, sending the output to a log file. Combine this with a file integrity monitor like AIDE to alert on changes to critical WordPress files. Configure email alerts for any checksum mismatches or newly created PHP files in wp-content/uploads.
- Enable WP_DEBUG_LOG in
wp-config.php. - Retain web server access logs for 30+ days.
- Run daily
wp core verify-checksumsvia cron. - Scan uploads directory for new PHP files.
- Set up email alerts for checksum failures.
crontab -e # add a line like:
0 2 * * * /usr/local/bin/wp core verify-checksums >> /var/log/wp-checksums.log 2>&1
0 3 * * * /usr/local/bin/wp plugin verify-checksums >> /var/log/wp-plugin-checksums.log 2>&1Check the log files for any "FAILED" messages. A failure indicates a core or plugin file does not match the official checksum, which should be investigated immediately.
If you would rather have engineers do this for you, see Linux server management, Windows server management or emergency malware cleanup.
Questions people ask
Why is my WordPress site suddenly sending visitors to unrelated spam pages?
The site is likely infected with malicious code that injects JavaScript or PHP redirects. Attackers exploit outdated plugins, themes, or weak credentials to place scripts that send visitors to spam URLs, often to generate ad revenue or phishing traffic.
Which WordPress files are most commonly compromised for redirects?
The most frequently compromised files are `wp-config.php`, `functions.php` in active themes, and core files like `index.php` or `wp-settings.php`. Attackers also target plugin files in `wp-content/plugins/` and the `.htaccess` file to add redirect rules.
Can a vulnerable plugin cause spam redirects even after I update WordPress?
Yes. A vulnerable plugin can retain a backdoor or malicious payload even after the core WordPress is updated. If the plugin isn’t patched or is re‑installed without cleaning, the hidden code can continue issuing redirects until the plugin is fully removed or cleaned.
What regular checks can I schedule to catch redirects before they affect users?
Schedule daily or weekly scans with a reputable malware scanner, monitor file integrity hashes for `wp-config.php`, theme `functions.php`, and `.htaccess`, and set up a cron job that fetches the homepage and checks for unexpected external URLs. Review server logs for sudden spikes in outbound requests to unknown domains.