【问题标题】:Query string restriction and redirection?查询字符串限制和重定向?
【发布时间】:2011-12-12 14:45:16
【问题描述】:

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

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

【问题讨论】:

  • 为什么要这样做?这应该是一种安全方法吗?

标签: php .htaccess redirect query-string querystringparameter


【解决方案1】:

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

【讨论】:

  • 详细说明:<?php foreach ($_GET as $k => $v) { if ($k != 's' && $k != 'p') { header("Location: 404.html", true, 404); } }。或者,您也可以使用 mod_rewrite 和 htaccess 来完成。
  • @Col:如果数组为空,则表示没有传递任何参数,因此应将其视为有效请求(或者我认为是这样)。
  • @Col:像这样? codepad.org/3MD9Ine5 // 如果你指的是我假设 $_GET 作为一个数组,我相信它是默认的。
  • @andre 是的,它有效,我的错。但是我认为循环 Get 有点多余。
【解决方案2】:

在 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】:

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

    $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 立即停止处理。没有它,重定向将在处理完所有剩余的数组键后发生。

    【讨论】:

      【解决方案4】:

      如果你想用 .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 变量,如果没有 ?s=: 则重定向或显示 404 页面:

      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;
      }
      

      你明白了。

      【讨论】:

      • 这实际上不起作用,因为 %{REQUEST_URI} 确实 包含查询字符串:来自该 Apache 网站 REQUEST_URI The path component of the requested URI, such as "/index.html". This notably excludes the query string which is available as as its own variable named QUERY_STRING.
      猜你喜欢
      • 2011-01-30
      • 1970-01-01
      • 2016-03-17
      • 2011-02-17
      • 2015-03-31
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多