【问题标题】:Prevent user from overwriting query string parameter with Nginx rewrite防止用户使用 Nginx 重写覆盖查询字符串参数
【发布时间】:2020-09-20 10:49:27
【问题描述】:

我有以下 Nginx 重写规则:

rewrite ^/([a-z0-9-]+)$ /post.php?slug=$1 last;

Nginx 现在将应用如下重写:

/a -> /post.php?slug=a
/a?slug=b -> /post.php?slug=a&slug=b

第二个例子有问题。如何防止访问者添加已通过重写规则添加的查询字符串参数?可能仍会提供其他查询字符串参数。期望行为示例:

/a -> /post.php?slug=a
/a?slug=b -> /post.php?slug=a
/a?foo=b -> /post.php?slug=a&foo=b

【问题讨论】:

    标签: nginx url-rewriting query-string


    【解决方案1】:

    您可以删除slug 查询参数:

    location ~ ^/(?<slug>[a-z0-9-]+)$ {
        if ($args ~ (.*)(^|&)slug=[^&]*(\2|$)&?(.*)) {
            set $args $1$3$4;
        }
        rewrite ^ /post.php?slug=$slug last;
    }
    

    这个复杂的正则表达式将从查询参数字符串中删除slug查询参数,无论它是在该字符串的开头、中间还是结尾。

    【讨论】:

      猜你喜欢
      • 2016-08-06
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      相关资源
      最近更新 更多