Created
April 25, 2017 00:38
-
-
Save wpsmith/1c48ad42ec790f9f27e865bc724a8311 to your computer and use it in GitHub Desktop.
Fixes the canonical redirection URL to have the same hostname as the original requested URL hostname. The best place for using this is when using a reverse proxy (or CDN like Akamai or Fastly) and the WordPress installation is path-based. For example, WP Engine does not support path-based installations where multiple installations have the same …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: WPS Canonical Redirection | |
Plugin URI: http://wpsmith.net/ | |
Description: Fixes the canonical redirection URL to have the same hostname as the original requested URL hostname. The best place for using this is when using a reverse proxy (or CDN like Akamai or Fastly) and the WordPress installation is path-based. For example, WP Engine does not support path-based installations where multiple installations have the same domain (e.g., features.weather.com) but have different paths (e.g., features.weather.com/us-climate-change and features.weather.com/climate25). | |
Author: Travis Smith <t@wpsmith.net> | |
Version: 0.0.1 | |
*/ | |
add_filter( 'redirect_canonical', 'wps_redirect_canonical', 10 ); | |
/** | |
* Filters the canonical redirect URL. | |
* | |
* Returning false to this filter will cancel the redirect. | |
* | |
* @param string $redirect_url The redirect URL. | |
* @param string $requested_url The requested URL. | |
* @return string $redirect_url Maybe fixed redirect URL. | |
*/ | |
function wps_redirect_canonical( $redirect_url ) { | |
$dest = parse_url( $redirect_url ); | |
// Since this is the canonical URL, we are assuming the site URL host | |
// is the same as the destination URL host. | |
$base_url = apply_filters( 'site_or_home_url', site_url() ); | |
$site = parse_url( $base_url ); | |
$base_url = preg_replace( '/^https?:\/\//i', '', $base_url ); | |
// Determine whether we need to change the redirect_url | |
// Compare the redirect url host with the site_url | |
if ( $dest['host'] !== $site['host'] ) { | |
// Replace the host with the host (+path from site_url()) | |
return str_replace( $dest['host'], $base_url, $redirect_url ); | |
} | |
// Return the same URL | |
return $redirect_url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment