安全/高效的方式使nginx重定向/?p = 123样式链接

时间:2016-01-05 07:04:58

标签: nginx nginx-location

我尝试将nginx 301重定向wordpress样式proc print data=work.test; var ID; run; ods pdf close; %macro reportgen(indsn=,varlist=, report_type=, title1=, footnote=, report_location=); %local i nextword; %let dsid =%sysfunc(open(&indsn)); %do i=1 %to %sysfunc(countw(&varlist)); %let nextword = %scan(&varlist, &i); %end; %mend reportgen; %macro reportgen(indsn=work.test,varlist=var1 var2 var4,report_type=,title1=,footnote=,report_location); 样式链接到固定网址。

If is evil和其他文档中,我认为危险的foo.com/?p=123语句是基于参数重定向的唯一方法,我发现像这样的配置似乎可以完成工作:

if

但是,我想,对于这种配置,nginx必须仔细阅读所有这些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 } 语句才能解决顶级if请求,这些请求可能并不理想。

"对"是什么?如何将这类重定向列表硬编码,同时最大限度地降低foo.com/语句的危险/成本?

1 个答案:

答案 0 :(得分:1)

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

另一个好主意是使用map代替if,因为它有一个更简洁的语法来定义长列表。

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

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

现在剩下要做的就是在主配置中使用定义的规则:

# 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块的级联可能看起来有些混乱,但是当你在那里放入很多规则时,你会看到这种方法的优势。