查询字符串限制和重定向?

时间:2011-10-21 13:48:48

标签: php .htaccess redirect query-string querystringparameter

是否可以将我的网站查询字符串参数限制为我分配的参数。这样做可以将我在批准列表中找不到的查询字符串参数的任何URL重定向到我的404页面吗?

例如,我只想让'?s ='和'?p ='作为查询字符串参数,因此如果访问www.mysite.com/?x=whatever,网站会将该用户重定向到我的404页面 - 如果{{1然后我的网站将显示相应的内容。

4 个答案:

答案 0 :(得分:2)

如果你想用.htaccess做,你可以做这样的事情:

RewriteCond %{REQUEST_URI} !(s=(.*)|404.html)
RewriteRule .* 404.html [R=404,L]

此外,您必须为?s =动态生成页面,因此请确保为index.php(或您正在使用的脚本)设置例外:

RewriteCond %{REQUEST_URI} !(^s=(.*)|404.html|index.php)
RewriteRule .* 404.html [R=404,L]

尚未经过测试,但这应该可行。

如果你想用PHP做,那么只需检查$ _GET变量并重定向或显示404页面如果没有?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;
}

你明白了。

答案 1 :(得分:1)

只需检查$_GET,然后查找是否有不允许的参数,然后重定向到您的404页面。

答案 2 :(得分:1)

在Apache上,您可以使用mod_rewrite ......以下内容:

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]

如果x的值有效,它将重定向到具有有效x参数的文件,否则它应该重定向到带有无效x参数的404处理程序(所以你如果你愿意,可以做一些喜欢它的事情。

在以下位置查看Apache mod_rewrite条件: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond

答案 3 :(得分:1)

创建一个允许的查询字符串参数列表,如下所示:

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

如果$ _GET数组包含除允许的键以外的任何键,则重定向用户:

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

使用exit立即停止处理。没有它,重定向将在处理完所有剩余的数组键后发生。