URL rewriting QUERY_STRING NGINX?

Viewed 405

I want to download any file from the host whose last address had the x-oss-process parameter. i.php?path=$1&x-oss-process=%1 Refer that $1 is the address of the referenced file and %1 is the value of the x-oss-process parameter Like the link below

https://dl.example.com/img/all/235868.jpg?x-oss-process=image/resize,m_lfit,h_200,w_200/quality,q_60

After referring this address to the following address

i.php?path=img/all/235868.jpg&x-oss-process=image/resize,m_lfit,h_200,w_200/quality,q_60

Now how do I write the nginx code to do this? Thank you for your help.

1 Answers

If the query argument name didn't contain any dash characters, like x_oss_process instead of x-oss-process, the solution would be much more simple. In that case we could check $arg_x_oss_process variable (see $arg_name variable description):

if ($arg_x_oss_process) {
    rewrite ^ /i.php?path=$uri;
}

The first parameter ^ is a regex that matches any string, $uri is a normalized request URI (without query arguments). All the query arguments would be added to the rewrited URI (see the rewrite directive description):

If a replacement string includes the new request arguments, the previous request arguments are appended after them. If this is undesired, putting a question mark at the end of a replacement string avoids having them appended, for example:

rewrite ^/users/(.*)$ /show?user=$1? last;

However since your query argument name contain dashes, the solution will be more complex (see this SO question for additional details). We would need to get the x-oss-process query argument value from $args variable using the map directive which shoud be placed outside the server block:

map $args $x_oss_process {
    ~(?:^|&)x-oss-process=([^&]*)    $1;
}

server {
    ...
    if ($x_oss_process) {
        rewrite ^ /i.php?path=$uri;
    }
    ...
}

This rewrite rule will rewrite

/img/all/235868.jpg?x-oss-process=image/resize,m_lfit,h_200,w_200/quality,q_60

request to the

/i.php?path=/img/all/235868.jpg&x-oss-process=image/resize,m_lfit,h_200,w_200/quality,q_60

This is slighly different from what you've been asked for (note the slash before img/all/235868.jpg URI part). I'd rather change i.php script to correctly process this, but if you want to strip this slash with nginx itself, you can use second map block:

map $args $x_oss_process {
    ~(?:^|&)x-oss-process=([^&]*)    $1;
}
map $uri $truncated_uri {
    ~/(.*)                           $1;
}

server {
    ...
    if ($x_oss_process) {
        rewrite ^ /i.php?path=$truncated_uri;
    }
    ...
}
Related