首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使nginx重定向/?p=123样式链接的安全/性能方法

使nginx重定向/?p=123样式链接的安全/性能方法
EN

Stack Overflow用户
提问于 2016-01-05 07:04:57
回答 1查看 325关注 0票数 0

我试图使nginx 301-重定向wordpress风格的foo.com/?p=123风格的链接到固定的URL。

如果是邪恶和其他文档中,我了解到危险的if语句是根据参数重定向的唯一方法,我发现这样的配置似乎可以完成任务:

代码语言:javascript
运行
复制
location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
}

location = / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;

    if ($arg_p = 4)  { return 301 /2012/12/hello-world; }
    if ($arg_p = 15) { return 301 /about;               }
    # ... a few hundred more lines like this
}

但是,我猜使用这种配置,nginx将不得不费力地遍历所有的if语句来解析顶级的foo.com/请求,这大概并不理想。

在最小化if语句的危险/成本的同时,有什么“正确”的方法来硬编码这样的大重定向列表?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-05 09:00:39

第一个好主意是将重定向规则放在一个单独的文件中。这将大大提高主配置的可读性。然后,带有规则的文件可以包含在包括指令中。

另一个好主意是使用地图而不是if,因为它有一个更清晰的语法来定义长列表。

假设您决定将规则放在/path/to/redirect/rules.conf中。然后,该文件的内容将如下所示:

代码语言:javascript
运行
复制
# Each map defines the set of rules for one set of conditions.
# The blocks must be sorted in order of priority: every next
# map block has a higher priority than the previous one.
map $arg_p $p_condition {
    default "";

    4              /2012/12/hello-world;
    15             /about;

    # You can use regular expressions
    ~^1[6-9]$      /some/page;
}

# By combining the condition variables you can implement
# some sort of and/or/not logic in your rules
map "${arg_p}#${arg_q}" $pq_condition {

    # Note that it is necessary to inherit the result
    # of the previous map block to preserve them. And this
    # is where the priority of the blocks comes from
    default $p_condition;

    # The values of p _and_ q are 4 and 15
    4#15           /2012/12/hello-world;

    # The value of p is 5 _or_ the value of q is 16
    ~"^5#.*"       /another/page;
    ~"^.*?#16"     /another/page;

    # The value of p is _not_ 8 _and_ the value of q is 30
    ~"^[^8]#30"    /the/very/special/page;
}

# The final block is of the highest priority. It defines
# the variable, which value will be used as the URL for redirection
map $args $url_to_redirect_to {

    # Don't forget this important line
    default $pq_condition;

    # Here's another type of condition: check if the t variable
    # is present in the list of GET paramters
    ~^(&|\?)t=.*$  /yet/another/page;
}

现在只剩下在主配置中使用定义的规则:

代码语言:javascript
运行
复制
# Note that map directives must be placed out of the `server` block
include /path/to/redirect/rules.conf;

server {
    ...

    location = / {
        ...

        if ($url_to_redirect_to != "") {
            rewrite ^ $url_to_redirect_to? permanent;
        }

        ...
    }

    ...
}

乍一看,map块的级联可能看起来有些混乱,但当您在其中放置了许多规则时,您将看到这种方法的优点。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34605948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档