Redirect with apache from root to path, while preserving query string

Redirect with Apache from root to path, while preserving query string

If you have a lot of pages indexed in search engines and decide to change a path in your web site, you probably want to redirect from the old URL to the new URL.

In this example, the web site search was previously at the root of the web site, with a parameter s, like this:, the new search path is now at the path /s (same parameter) like this:

NOTE: There are no other pages with query strings on this web site. If that is not your scenario, this will probably not work. Of course, replace with your own web site domain.

To redirect from the old path to the new path, add the following at the bottom of /etc/apache2/sites-enabled/, before the /VirtualHost tag:

  # initialize RewriteEngine
  RewriteEngine On

  # exclude actual search pages, with s in path
  RewriteCond %{REQUEST_URI} !=/s

  # If the querystring has at least 1 character
  RewriteCond %{QUERY_STRING} ^.+

  # Rewrite requests to the root
  RewriteRule ^/?$ [L,QSA]

Restart apache to make it take effect

systemctl restart apache2.service

Now, pages with query strings will be redirected from to