How to Remove Query String from URL and Redirect in Apache


apache remove query string from url

When you move your web pages from one location to another, it’s essential to redirect your old page to its new location. However, sometimes, you may need to remove its query string while redirecting to the new location. Apache allows you to do it easily with just 1 line of code. Let us take a look at how to remove query string from URL and redirect in Apache.

 

How to Remove Query String from URL and Redirect in Apache

Here are the steps to remove query string from URL and redirect in Apache web server.

Before you proceed, please ensure that you have enabled .htaccess (mod_rewrite) in Apache. If not, then here’s how you can do it:

 

Place your .htaccess file in the root document folder of your website (/var/www/html)

 

1. Open .htaccess file

Open a terminal session or SSH into your Linux system. Open .htaccess file in a text editor


$ sudo vim /var/www/html/.htaccess

 

2. Remove query string from URL and redirect

Let’s say you have a URL /product.php that accepts multiple query string values in URL such /product.php?car=Tesla&model=V11

Let’s say you want to redirect these URLs to a new page /product-list.php without any query string parameters

In that case, simply add the following line to your .htaccess file

RewriteRule ^product\.php$ /product-list\.php? [L,R=301]

 

Please note, there is a question mark (‘?’) after the new URL /product-list\.php that makes all the difference. It removes all the query string from original URI before redirecting it.

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

That’s it! Now Apache will remove the query string from URL and only then redirect 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!