Skip to content

Instantly share code, notes, and snippets.

@PatelUtkarsh
Last active February 13, 2024 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatelUtkarsh/005ed13a0e7a2364eb5230a9393d96fb to your computer and use it in GitHub Desktop.
Save PatelUtkarsh/005ed13a0e7a2364eb5230a9393d96fb to your computer and use it in GitHub Desktop.
WordPress network site with different home url and site adress with reverse proxy redirects trailing slash to site address instead of home url.
<?php
/**
* Plugin name: Redirect canonical to home URL for trailing slash.
* Description: Fix for WordPress network site with different homeurl and site address with reverse proxy, which redirects non-trailing slash to site address instead of home url.
* Version: 1.0
* Author: Utkarsh
* Author URI: https://utkarshpatel.com
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
namespace Utkarsh\RedirectCanonical;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Redirect canonical requests to the correct URL based on home_url.
*
* This is a temporary solution to fix the issue where host and site domain are different.
* We override `HTTP_HOST` with home url from wp-config.php and test it on staging first.
*
* @param string $redirect_url The redirect URL.
*
* @return string
*/
function redirect_to_host( $redirect_url ) {
$home_host = parse_url( home_url(), PHP_URL_HOST );
$details = get_blog_details( get_current_blog_id() );
$site_host = $details->domain;
$redirect_host = parse_url( $redirect_url, PHP_URL_HOST );
// If redirecting url host is blog address and home host is NOT same as site url then replace host with homeurl.
if ( $site_host === $redirect_host && $home_host !== $site_host ) {
$redirect_url = str_replace( $site_host, $home_host, $redirect_url );
}
return $redirect_url;
}
add_filter( 'redirect_canonical', __NAMESPACE__ . '\\redirect_to_host' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment