Auto Trim and Redirect Spammy URL Endings in WordPress

Updated 10/30/2024, Posted 10/30/2024 by James Parsons James Parsons 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

Hi, I'm James Parsons! I founded Content Powered, a content marketing agency where I partner with businesses to help them grow through strategic content. With nearly twenty years of SEO and content marketing experience, I've had the joy of helping companies connect with their audiences in meaningful ways. I started my journey by building and growing several successful eCommerce companies solely through content marketing, and I love to share what I've learned along the way. You'll find my thoughts and insights in publications like Search Engine Watch, Search Engine Journal, Forbes, Entrepreneur, and Inc, among others. I've been fortunate to work with wonderful clients ranging from growing businesses to Fortune 500 companies like eBay and Expedia, and helping them shape their content strategies. My focus is on creating optimized content that resonates and converts. I'd love to connect – the best way to contact me is by scheduling a call or by email.