How to Remove Query String from URL and Redirect in NGINX


nginx remove query string from url

When you move your web pages to a new location, you might want to remove its query string variables before redirecting them. NGINX makes it really easy to strip off all query string parameters before redirecting them. Let us take a look at how to remove query string from URL and redirect in NGINX web server.

 

How to Remove Query String from URL and Redirect in NGINX

Here are the steps to remove query string from URL and redirect in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

2. Remove query string from URL and redirect

Let’s say you have a URL /product.php that accepts various query parameters in URL such as /product.php?brand=apple&model=iphone&version=10

Let’s say you want to redirect all these pages to a single page /product-catalog.php after removing all query string.

In that case, add the following rewrite rule to your location block of /product.php

location ^~ /product.php {
    rewrite ^/product.php$ /product-catalog.php? permanent;
}

Please note, there is a question mark (?) in the rewrite rule, after the new location, that makes all the difference. It is responsible for stripping off any query string before redirecting it.

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

Now NGINX will remove any query string parameters in your URL before redirecting it to new location.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!