Skip to content

Instantly share code, notes, and snippets.

@justingreerbbi
Last active December 23, 2020 15:42
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 justingreerbbi/5f4f2573f5cf04c599f5f05b8910baf6 to your computer and use it in GitHub Desktop.
Save justingreerbbi/5f4f2573f5cf04c599f5f05b8910baf6 to your computer and use it in GitHub Desktop.
Simple custom redirect hook for WordPress with domain whitelisting. Simply download the file
<?php
/**
* Plugin Name: Custom Redirect Trigger
*
* This plugin allows all redirects to be processed. It can be dangerous if used incorrectly. This includes
* not adding a whitelist domain redirect. Having this wide open will all hackish redirects.
*/
class Custom_Redirect_Rewrites {
/*
* Add domains without http or https in the array below. only use the host. no exstensions or prefixes.
*/
public $whitelisted_redirects = array(
'allowed-domain.com',
'allowed-domain2.com'
);
function create_rewrite_rules( $rules ) {
global $wp_rewrite;
$newRule = array( 'crt/(.+)' => 'index.php?crt=' . $wp_rewrite->preg_index( 1 ) );
$newRules = $newRule + $rules;
return $newRules;
}
function add_query_vars( $qvars ) {
$qvars[] = 'crt';
return $qvars;
}
function flush_rewrite_rules() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function template_redirect_intercept() {
global $wp_query;
if ( $wp_query->get( 'crt' ) && $wp_query->get( 'crt' ) == 'redirect' ) {
// Check the provided redirect against the whitelisted redirect
$redirect_uri = ! empty( $_GET['redirect_crt_uri'] ) ? $_GET['redirect_crt_uri'] : false;
if ( ! $redirect_uri ) {
exit( 'No redirect provided' );
}
$redirect_host = parse_url( $redirect_uri, PHP_URL_HOST );
if ( ! in_array( $redirect_host, $this->whitelisted_redirects ) ) {
exit( 'Unauthorized Redirect URL' );
}
wp_redirect( $redirect_uri );
exit;
}
}
}
$WPOSSO_Rewrites = new Custom_Redirect_Rewrites();
add_filter( 'rewrite_rules_array', array( $WPOSSO_Rewrites, 'create_rewrite_rules' ) );
add_filter( 'query_vars', array( $WPOSSO_Rewrites, 'add_query_vars' ) );
add_filter( 'wp_loaded', array( $WPOSSO_Rewrites, 'flush_rewrite_rules' ) );
add_action( 'template_redirect', array( $WPOSSO_Rewrites, 'template_redirect_intercept' ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment