Search code examples
php.htaccesshttp-redirectquery-stringquerystringparameter

Query string restriction and redirection?


Is it possible to restrict my websites query string parameters to those I allocate. In doing so can I redirect any URLs with query string parameters not found on my approved list to my 404 page?

For example I want only '?s=' and '?p=' to be allowed as query string parameters, therefore if www.mysite.com/?x=whatever is accessed the site will redirect that user my 404 page - if www.mysite.com/?s=whatever then my site will display the appropriate content.


Solution

  • Create a list of allowed query string parameters like this:

    $allowed_parameters = array( 's', 'q' );
    

    If the $_GET array contains any key other than those allowed, redirect the user:

    foreach ( $_GET as $key => value ) {
        if ( ! in_array( $key, $allowed_parameters ) ) {
            header( "Location: http://www.mysite.com/error404.html" );
            exit;
       }
    }
    

    Use exit to stop processing immediately. Without it, the redirect will happen after all remaining array keys are processed.