Last active
October 24, 2023 13:07
-
-
Save rmpel/942418855f2a9d677796b0d991ce64fd to your computer and use it in GitHub Desktop.
Prevent redirect loops in WordPress
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: Prevent Redirect Loop | |
* Description: Prevent redirect loops if user adds a redirect to the same page in Yoast SEO Premium or other plugins. | |
* Version: 1.0.0 | |
* Author: Remon Pel | |
*/ | |
// Prevent redirect loops. | |
add_filter( | |
'wp_redirect', | |
function ( $location ) { | |
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.MissingUnslash | |
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized | |
// get the current request. | |
$request = ! empty( $_SERVER['REQUEST_URI'] ) ? trim( $_SERVER['REQUEST_URI'], '/' ) : '/'; | |
// add the current GET params to the request. | |
$request .= ! empty( $_SERVER['QUERY_STRING'] ) ? '?' . trim( $_SERVER['QUERY_STRING'] ) : ''; | |
// phpcs:enable WordPress.Security.ValidatedSanitizedInput.MissingUnslash | |
// phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized | |
// use wp_parse_url to get the path and the GET params of both the request and the location. | |
$request_parsed = wp_parse_url( $request ); | |
$location_parsed = wp_parse_url( $location ); | |
$request_parsed['path'] = trim( $request_parsed['path'], '/' ); | |
$location_parsed['path'] = trim( $location_parsed['path'], '/' ); | |
// if the request and the location are the same, we have a redirect loop. | |
if ( $request_parsed['path'] === $location_parsed['path'] && $request_parsed['query'] === $location_parsed['query'] ) { | |
header( 'X-Redirect-Loop-Prevented-By:' . basename( __FILE__ ) ); | |
return false; | |
} | |
return $location; | |
}, | |
10, | |
1 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment