Auto Trim and Redirect Spammy URL Endings in WordPress
I noticed that both my site and my client's websites were getting spammy-looking visits to URLs that looked like:
- domain.com/blog-post/null
- domain.com/blog-post/undefined
- domain.com/blog-post/1000
These are either generated by spam or by some rogue SEO plugin. Either way, they are low value, and somehow users are ending up here. Instead of this ending up a 404, I think it's best to redirect them to the page.
Additionally, WordPress likes to create a feed for every individual blog post for some reason:
- domain.com/blog-post/feed/
Between these four types of error URLs, things can get pretty messy with Search Console errors and 404 warnings in various Analytics suites.
Let's clean these up.
I put together this simple bit of code to fix this. Just drop it at the bottom of your theme's functions.php file:
// Automatically redirect spam pages: /undefined, /1000, /null, /feed
function custom_redirect_trim_endings() {
$request_uri = $_SERVER['REQUEST_URI'];
if (preg_match('#/(feed|undefined|1000|null)(/)?$#', $request_uri)) {
$new_url = rtrim(preg_replace('#/(feed|undefined|1000|null)(/)?$#', '', $request_uri), '/');
if ($new_url === '') $new_url = '/';
wp_redirect($new_url, 301);
exit;
}
}
add_action('template_redirect', 'custom_redirect_trim_endings');
Now these will automatically redirect and they won't appear as 404 errors. You can test this by adding one of these after the URL you're currently on on my site. If you add /1000 or /feed, etc, then you're redirected as intended.
Much better for user experience!
Did this help you? Let me know in the comments!
Comments