Avoid nginx escaping query parameters on proxy_pas

2019-06-14 14:30发布

问题:

I to proxy /api on a domain, I have this location block.

location ^~ /api/ {
    rewrite_log on;
    rewrite ^/api/(.*) /$1$is_args$args break;
    proxy_pass http://127.0.0.1:1337;
}

It works fine as long as the URLs do not have query parameters, but as soon as they do, I get errors on the upstream server like these Could not find path: /records%3fname=hoegh.io

The %3f in question here is an URL encoded ?, and since it's URL encoded, the upstream server does not recognize it. That might be retarded, but I was hoping it was possible to get nginx to handle this correctly (ie. not escape the URL before passing it to the proxy).

Any ideas?

回答1:

You don't need to do anything. $args is passed along automatically.

If you wish to modify the $args that are passed you have to override.

set $args "foo=bar";

for instance.

Working solution should go as follows:

location ^~ /api/ {
    rewrite_log on;
    rewrite ^/api/(.*) /$1 break;
    proxy_pass http://127.0.0.1:1337;
}


回答2:

Have you tried this instead? It's generally not needed to add the query string as Nginx adds it automatically:

rewrite ^/api/(.*) /$1? break;