• Resolved ur_communications

    (@ur_communications)


    The issue is, we have apache rules for placing certain URLs behind authentication. The WP feature of stripping out special characters before querying the database allows users to bypass auth rules by adding special characters in the URL.

    Example: https://www.mysite.com/my-pa*ge retrieves https://www.mysite.com/my-page, even though https://www.mysite.com/my-page requires authentication.

    Is there a creative solution that would allow my site to reject these requests and display a 404 instead?

    I’d like to do something like this:

    
    function block_special_chars($title) {
      // accept only letters, numbers, and hyphens
      if (preg_match("/^[A-Za-z0-9-]+$/", $title)) {
        return $title;
      } else {
        return "404";
      }
    }
    add_filter('sanitize_title', 'block_special_chars');
    

    I thought this would work, however the $title passed is already filtered. Is there a hook before this I can use to accomplish what I need?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    Maybe do something with the “request” filter? Your callback is passed all the query vars established by the request. Check if “name” or “pagename” vars are set. If so apply your preg_match() test to determine if extended chars in the slug are requested or not. If so, you can unset/set the vars needed to return a 404 error instead of fulfilling the request.

    Thread Starter ur_communications

    (@ur_communications)

    Maybe do something with the “request” filter? Your callback is passed all the query vars established by the request. Check if “name” or “pagename” vars are set. If so apply your preg_match() test to determine if extended chars in the slug are requested or not. If so, you can unset/set the vars needed to return a 404 error instead of fulfilling the request.

    This works! Thank you.

    
    function filter_qvar_value($value) {
      if (preg_match("/^[A-Za-z0-9-]+$/", $value) || $value == '') {
        return $value;
      } else {
        return "404";
      }
    }
    
    function remove_special_characters( $qvars ) {
      return array_map("filter_qvar_value", $qvars);
    }
    
    add_filter( 'request', 'remove_special_characters' );
    
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Help stop titles / slugs with special characters from being queried’ is closed to new replies.