Query string restriction and redirection?
-
10-02-2021 - |
문제
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.
해결책
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.
다른 팁
If you want to do it with .htaccess, you can make something like this:
RewriteCond %{REQUEST_URI} !(s=(.*)|404.html)
RewriteRule .* 404.html [R=404,L]
Also, you must be generating pages for ?s= dynamically, so make sure to make an exception for index.php (or the script you are using):
RewriteCond %{REQUEST_URI} !(^s=(.*)|404.html|index.php)
RewriteRule .* 404.html [R=404,L]
Haven't tested, but this should work.
If you want to do it with PHP, then simply check the $_GET variable and redirect or display the 404 page if there's no ?s=:
if (!(isset($_GET['s'])) {
header('HTTP/1.0 404 Not Found');
header('Expires: Thu, 19 Nov 1981 08:52:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, private');
readfile('404.html');
exit;
}
You get the point.
Just check the $_GET
and find if there are disallowed parameters then redirect to your 404 page.
On Apache you could use mod_rewrite... something along the lines of:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^x=(allowed_values_of_x)$
RewriteRule ^path/in/uri$ /redirect/to/file?withquery=%1 [L]
RewriteCond %{QUERY_STRING} ^x=(.*)$
RewriteRule ^path/in/uri$ /redirect/to/404?withquery=%1 [R=404,L]
If values of x
are valid it'll redirect to a file with the valid x
parameter, otherwise it should redirect to a 404 handler with the invalid x
parameter (so you can do something fancy with it if you wish).
Look at Apache mod_rewrite conditionals at: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond