user2349115
user2349115

Reputation: 1286

How to send request_uri as query parameter in proxy_pass in nginx

I have below nginx configuration

server {
listen 80;
client_max_body_size 10M;
keepalive_timeout    15;
server_name mysite.com;

location / {
    proxy_pass http://anothersite.com
}
}

Above is working, but I need something like below:

location / { proxy_pass http://anothersite.com?q=request_uri so I can pass request_uri as a query parameter.

Can you please provide correct syntax for passing request_uri as query parameter.

Thanks.

Upvotes: 2

Views: 1880

Answers (1)

Nopeman
Nopeman

Reputation: 56

You can simply rewrite your request_uri using regular expressions.

location / {
    rewrite ^/(.+)$ ?q=$1
    proxy_pass http://anothersite.com;
}

The rewrite rule matches any request_uri starting with / and captures any non-empty string which comes afterwards (.+). It then rewrites the request_uri to ?q= followed by whatever came after the /. Since your proxy_pass directive doesn't end with an / it will append the rewritten request_uri to the proxy target.

So a request to http://yoursite.com/some/api would be rewritten and proxy-passed to http://anothersite.com?q=some/api

Hope that is what you want!

Upvotes: 1

Related Questions