How to transform query string parameters in nginx?

by aliya.yundt , in category: General Help , 3 months ago

How to transform query string parameters in nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by coty_beier , 3 months ago


To transform query string parameters in Nginx, you can use the rewrite directive. The rewrite directive allows you to modify the request URI based on certain conditions.

Here is an example of how you can transform query string parameters in Nginx:

  1. Open your Nginx configuration file using a text editor. The configuration file is usually located at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf.
  2. Inside the server block or the location block where you want to perform the transformation, add the following code using the rewrite directive:
location /example {
  rewrite ^/example?key1=(.*)$ /example/new?key1=$1 last;

This example will transform a URL like /example?key1=value1 into /example/new?key1=value1. The value of the key1 parameter remains the same.

  1. Save the configuration file and exit the text editor.
  2. Test the Nginx configuration to ensure there are no syntax errors:
sudo nginx -t

  1. If the test is successful, reload Nginx to apply the new configuration:
sudo systemctl reload nginx

Now, when a request is made to /example?key1=value1, Nginx will internally transform it to /example/new?key1=value1 without changing the client's visible URL.

You can modify the regex pattern ^/example?key1=(.*)$ based on your specific requirements to match different query string parameter patterns.