apache redirect query parameters

How to Rewrite URL with Parameters in Apache

Sometimes you may need to rewrite URL with parameters in Apache server. This is very common requirement for websites & blogs as they keep adding new URLs and retire old ones. You can easily do this using mod_rewrite module in Apache. In this article, we will look at how to redirect one URL to another while preserving the requested URL’s query parameters.

How to Rewrite URL with Parameters in Apache

Here are the steps to rewrite URL with parameters in Apache.

1. Enable mod_rewrite

First, you need to enable mod_rewrite in Apache server, if you have not done it already. Otherwise, based on your Linux distribution, follow the steps below to enable mod_rewrite.


Open terminal and run the following command to enable mod_rewrite.

$ sudo a2enmod rewrite


Open Apache configuration file in a text editor.

$ sudo vi /etc/apache2/httpd.conf
$ sudo vi /etc/httpd/httpd.conf

Look for the following line.

#LoadModule rewrite_module modules/mod_rewrite.so

Uncomment it by removing # at its beginning. If you don’t find this line, add it afresh.

Also look for the following Directory tag and change AllowOverride from None to All.

. . .
<Directory /var/www/html>
. . .
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
AllowOverride All
. . .
. . .

2. Rewrite URL with parameters

Open .htaccess file at your website’s document root.

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

Let us say you want to redirect /product?id=10&category=20 to /items?id=10&category=20 then add the following lines to your .htaccess file.

RewriteEngine On
RewriteRule ^product_id?$ /items?%{QUERY_STRING} [NC,L]

In the above code, the first line enables mod_rewrite if it is not already enabled. Next, the RewriteRule matches URLs starting with /product_id and redirects them to URLs beginning with /items. It also appends the query string from original URL to redirected URL, with the help of QUERY_STRING server variable. QUERY_STRING stores the query string from original requested URL.

3. Restart Apache Server

Restart Apache server to apply changes.

$ sudo service apache2 restart

That’s it. As you can see it is very easy to rewrite URLs with query string parameters. You can modify it according to your requirements.

Also read:

How to Combine Two Files in Linux
How to Rewrite URL to Another URL in Apache
How to Filter Logs By Date/Time in Linux
How to Verify Checksum in Linux
How to Create PDF in Python

Leave a Reply

Your email address will not be published. Required fields are marked *