将查询字符串重写为路径参数 [英] Rewrite query string to path params
问题描述
我有以下 nginx 配置来托管我的图像服务:
I have the following configuration of nginx that hosts my image service:
upstream thumbor {
server localhost:8888;
}
server {
listen 80;
server_name my.imageserver.com;
client_max_body_size 10M;
rewrite_log on;
location ~ /images {
if ($arg_width="10"){
rewrite ^/images(/.*)$ /unsafe/$1 last;
}
rewrite ^/images(/.*)$ /unsafe/$1 last;
}
location ~ /unsafe {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header HOST $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://thumbor;
proxy_redirect off;
}
location = /favicon.ico {
return 204;
access_log off;
log_not_found off;
}
}
我正在尝试重写以下网址:
I am trying to rewrite the following urls:
来自
到
这很容易,当我想允许应该像这样转到 url 路径的查询字符串时,问题就开始了:
which is quite easy, the problem begins when I want to allow query string that should go to the path of the url like so:
来自
到
如果查询字符串的顺序无关紧要会更好.
Also it will be better if the order of the query strings won't matter.
我尝试使用:$arg_width 但它似乎不起作用.
I tried using: $arg_width but it didn't seem to work.
在 ubuntu 上使用 nginx 1.6.1.
Using nginx 1.6.1 on ubuntu.
非常感谢您的帮助.
推荐答案
处理查询参数总是很困难(对于 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 {
(...)
这篇关于将查询字符串重写为路径参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!