Content Marketing

WordPress: How To Redirect All RSS Feeds To One Destination

While reviewing Google Search Console, one issue that I kept encountering was URLs ending in /feed/ causing issues. While it’s pretty ingenious of the WordPressCMS to add RSS feeds to every bit of content – posts, tags, categories, comments, etc. – the feature is unnecessary. It produces a ton of internal paths for Google to crawl that have no impact on search engine visibility.

While feed readers aren’t as popular as once, I’d rather my readers subscribe to my FeedPress endpoint rather than these individual feeds on my site. My FeedPress URL is https://feed.martech.zone which consumes my primary feed from https://martech.zone/feed. FeedPress allows me to do some additional customization to my feed as well as monitor how many readers and third parties are consuming the feed.

Redirect All WordPress Feed URLs

This PHP code snippet is a WordPress function that redirects all feed URLs to a specific destination except your primary feed. We need to leave the primary feed so we don’t have an infinite loop. Let’s break it down:

// Redirect all /feed/ URLs to the 
function redirect_feed_urls() {
    // Get the current URL path
    $current_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    // Check if the request is for a feed URL that is not the root path
    if (preg_match('/\/feed\/?(\?.*)?$/', $_SERVER['REQUEST_URI']) && $current_path !== '/feed/') {
        // Redirect to the feed URL on martech.zone
        wp_redirect('https://feed.martech.zone', 301);
        exit;
    }
}
add_action('template_redirect', 'redirect_feed_urls');
  1. The function redirect_feed_urls() is defined.
  2. It first gets the current URL path using parse_url() and $_SERVER['REQUEST_URI'].
  3. The function then checks two conditions using an if statement:
    a. It uses a regular expression (regex) to check if the current URL ends with ‘/feed/’ or ‘/feed’ (with or without a trailing slash), potentially followed by query parameters.
    b. It also ensures that the current path is not exactly ‘/feed/’.
  4. If both conditions are met, the URL is a feed URL, not the root feed URL.
  5. In this case, the function redirects the user to ‘https://feed.martech.zone’ using the wp_redirect() function. The 301 parameter indicates a permanent redirect.
  6. The exit command ensures that no further code is executed after the redirect.
  7. Finally, the function is hooked into WordPress’s ‘template_redirect’ action using add_action(). This means the function will run during WordPress’s template loading process.

This approach can be beneficial for maintaining consistent feed URLs, especially if you’ve moved your feed to an external service or want to standardize feed access across multiple WordPress installations.

Exclude a User Agent and Redirect All Other Feed Requests

You can also strengthen this further so that no end user can ever access your primary feed on your domain and is redirected. In the example below, we allow the FeedPress user agent to consume the primary feed, but anyone else is redirected.

// Redirect all /feed/ URLs except for FeedPress user agent
function redirect_feed_urls() {
    // Get the current URL path
    $current_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    // Check if the request is for a feed URL that is not the root path
    if (preg_match('/\/feed\/?(\?.*)?$/', $_SERVER['REQUEST_URI']) && $current_path !== '/feed/') {

        // Check if the User Agent contains "FeedPress"
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        if (stripos($user_agent, 'FeedPress') === false) {
            // Redirect to the feed URL on martech.zone for non-FeedPress user agents
            wp_redirect('https://feed.martech.zone', 301);
            exit;
        }
        // If it's FeedPress, allow access to domain.com/feed/
    }
}
add_action('template_redirect', 'redirect_feed_urls');

Exclude IP Addresses and Redirect All Other Feed Requests

In the example below, we allow some IP addresses to consume the primary feed, but anyone else is redirected.

// Redirect all /feed/ URLs except for specific IP addresses
function redirect_feed_urls() {
    // Array of allowed IP addresses
    $allowed_ips = array(
        '123.456.789.0',
        '987.654.321.0'
        // Add more IP addresses as needed
    );

    // Get the current URL path
    $current_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    // Check if the request is for a feed URL that is not the root path
    if (preg_match('/\/feed\/?(\?.*)?$/', $_SERVER['REQUEST_URI']) && $current_path !== '/feed/') {

        // Get the visitor's IP address
        $visitor_ip = $_SERVER['REMOTE_ADDR'];

        // Check if the visitor's IP is not in the allowed list
        if (!in_array($visitor_ip, $allowed_ips)) {
            // Redirect to the feed URL on martech.zone for non-allowed IPs
            wp_redirect('https://feed.martech.zone', 301);
            exit;
        }
        // If it's an allowed IP, allow access to domain.com/feed/
    }
}
add_action('template_redirect', 'redirect_feed_urls');

Exclude A Request with an API Key and Redirect All Other Feed Requests

Using an API key in the URL querystring is a great way to control access to your feed. Here’s how you can modify the code to allow access to domain.com/feed/ for requests that include a valid API key in the querystring while redirecting all others to https://feed.martech.zone:

// Redirect all /feed/ URLs except for those with a valid API key
function redirect_feed_urls() {
    // Set your API key here
    $valid_api_key = 'your_secret_api_key_here';

    // Get the current URL path
    $current_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    // Check if the request is for a feed URL that is not the root path
    if (preg_match('/\/feed\/?(\?.*)?$/', $_SERVER['REQUEST_URI']) && $current_path !== '/feed/') {

        // Get the API key from the querystring
        $provided_api_key = isset($_GET['api_key']) ? $_GET['api_key'] : '';

        // Check if the provided API key is valid
        if ($provided_api_key !== $valid_api_key) {
            // Redirect to the feed URL on martech.zone for invalid or missing API keys
            wp_redirect('https://feed.martech.zone', 301);
            exit;
        }
        // If the API key is valid, allow access to domain.com/feed/
    }
}
add_action('template_redirect', 'redirect_feed_urls');

This code:

  1. Defines a $valid_api_key variable. Replace ‘your_secret_api_key_here’ with your actual API key.
  2. Checks if the request is for a feed URL (as before).
  3. If it is, it then checks for an ‘api_key’ parameter in the querystring using $_GET['api_key'].
  4. It compares the provided API key with the valid API key.
  5. If the API key is invalid or missing, it redirects to https://feed.martech.zone.
  6. If the API key is valid, it allows access to domain.com/feed/ without redirection.

With this setup, a valid request would look like:

https://domain.com/feed/?api_key=your_secret_api_key_here

This method offers several advantages:

  • It’s more flexible than IP-based restrictions, allowing authorized access from any location.
  • It’s more secure than user agent checks, which can be easily spoofed.
  • You can easily change the API key if needed, or even implement multiple API keys for different users or services.

Remember to choose a strong, unique API key and keep it secret. To prevent abuse of the API key, consider implementing additional security measures, such as rate limiting.

Only Redirect Your Primary Feed Based on User Agent

function redirect_feed_urls() {
    // Get the current URL path
    $current_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    // Get the current URL's query string 
    $query_string = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);

    // Construct the full feed URL with query string if present
    $feed_url = 'https://feed.martech.zone';
    if ($query_string) {
        $feed_url .= '?' . $query_string;
    }

    // Check if the request is for a feed URL with no subdirectories AND the domain matches the current domain
    $current_domain = parse_url(home_url(), PHP_URL_HOST); // Get the current site's domain

    if ( 
        preg_match('/^\/feed\/?(\?.*)?$/', $_SERVER['REQUEST_URI']) &&  // Check for /feed/ with optional query string
        $current_path !== '/feed/' && // Exclude the root /feed/ path
        $current_domain === parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) // Check if the referrer domain matches the current domain
    ) {
        // Check if the User Agent contains "FeedPress"
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'FeedPress') !== false) {
            // Display the content of https://martech.zone/feed/
            include( get_home_path() . 'feed' ); // Assuming your feed template is at the root
            exit; 
        } else {
            // Redirect other users to https://feed.martech.zone/ (with query string if present)
            wp_redirect($feed_url, 301); 
            exit;
        }
    }
}
add_action('template_redirect', 'redirect_feed_urls');

This code handles requests to feed URLs on a WordPress site. It differentiates between requests from FeedPress and other users. FeedPress gets the raw feed content, while others are redirected to a specific feed URL, potentially with query parameters preserved. This can be helpful in managing feed syndication and ensuring consistent feed access.

As soon as I instituted this, the number of feed subscribers I had skyrocketed, so it was apparent that many endpoints and some people were subscribed to these subfeeds. I’m glad they’re now collectively consuming my primary feed.

Photo of Douglas Karr

Douglas Karr

Douglas Karr is a fractional Chief Marketing Officer specializing in SaaS and AI companies, where he helps scale marketing operations, drive demand generation, and implement AI-powered strategies. He is the founder and publisher of Martech Zone, a leading publication in marketing technology, and a trusted advisor to startups and enterprises… More »
Back to top button
Close

Adblock Detected

We rely on ads and sponsorships to keep Martech Zone free. Please consider disabling your ad blocker—or support us with an affordable, ad-free annual membership ($10 US):

Sign Up For An Annual Membership