How do I properly redirect outbound links with special characters

Right after posting, I learned a couple things, most importantly, that url encoding is done differently for paths and queries and one of our search sources treats the search query as a path, so I had to use rawurlencode for the path; and urlencode for the others. This is why I was receiving inconsistent results from trying different search engines.

There are a few sanitization functions within wp_redirect as well.

function search_redirect_form() {
  if (is_search() && ! empty( $_GET['simple'] ) ) {
       if ( isset( $_GET['simple'] ) && $_GET['simple'] === 'dogpile') {
            $query = urlencode( $_GET["s"] )
            wp_redirect(esc_url('url1' . $query));
            exit(); 
        }
        if ( isset( $_GET['simple'] ) && $_GET['simple'] === 'altavista') {
            $query = rawurlencode( $_GET["s"] );
            wp_redirect(esc_url('url2'. $query .'/field/all/mode/all/conn/and/order/nosort'));
            exit(); 
        }
        if ( isset( $_GET['simple'] ) && $_GET['simple'] === 'askjeeves') {
            $query = urlencode( $_GET["s"] )
            wp_redirect(esc_url('url3' . $query));
            exit();  
        }
        else { 
            $query = urlencode( $_GET["s"] )
            wp_redirect(esc_url($home_url . "?s=" . $query));
            exit();  
        }   
  }
} add_action( 'pre_get_posts', 'search_redirect_form', 1 );

Leave a Comment