Auto Trim and Redirect Spammy URL Endings in WordPress

James Parsons by James Parsons Updated Oct 30th, 2024 0 Comments

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!

Related Code Snippets

Written by James Parsons

James Parsons is the founder and CEO of Content Powered, a premier content marketing agency that leverages nearly two decades of his experience in content marketing to drive business growth. Renowned for founding and scaling multi-million dollar eCommerce businesses through strategic content marketing, James has become a trusted voice in the industry, sharing his insights in Search Engine Watch, Search Engine Journal, Forbes, Entrepreneur, Inc, and other leading publications. His background encompasses key roles across various agencies, contributing to the content strategies of major brands like eBay and Expedia. James's expertise spans SEO, conversion rate optimization, and effective content strategies, making him a pivotal figure in the industry.