且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将查询字符串重写为路径参数

更新时间:2023-02-24 10:37:05

处理查询参数总是很困难(对于 Apache 也是如此).

Working with query arguments is always hard (this is also true with Apache).

但在你的例子中,当你这样做时:

But in your example when you do:

location ~ /images { 
    if ($arg_width="10"){
        rewrite ^/images(/.*)$ /unsafe/$1 last;
    }
    rewrite ^/images(/.*)$ /unsafe/$1 last;
}

我看不出 2 次重写之间有任何区别……所以这可能是它不起作用的原因.

I do not see any difference between the 2 rewrites... so that's maybe why it is not working.

无论如何,您可以尝试类似的方法(基于 这个线程):

Anyway you could maybe try something like that (based on this thread):

location ^~ /images {
    # get there only if we have a query string
    if ($is_args) {
        set $width ""; 
        set $height "";
        if ($args ~* "(?:^|&)width=([^&]+)") { 
            set $width $1; 
        }
        if ($args ~* "(?:^|&)height=([^&]+)") { 
            set $height $1; 
        }

        # string concatenation using sort of bash syntax
        set $dim "${width}x${height}";
        # maybe we should add a control here on $dim !='x'...

        # the ? here prevent query string from being appended
        rewrite ^/images(/.*)$ /unsafe/$dim/$1? last;
    }
    rewrite ^/images(/.*)$ /unsafe/$1 last;
} 
location ~ /unsafe {
    (...)