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: http://example.com/?s=, the new search path is now at the path /s (same parameter) like this: http://example.com/s?s=.

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 example.com 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/example.com.conf, before the /VirtualHost tag:

  # initialize RewriteEngine
  RewriteEngine On

  # exclude actual search pages, with s in path
  # https://wiki.apache.org/httpd/RewriteCond
  RewriteCond %{REQUEST_URI} !=/s

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

  # Rewrite requests to the root
  RewriteRule ^/?$ http://example.com/s [L,QSA]

Restart apache to make it take effect

systemctl restart apache2.service

Now, pages with query strings will be redirected from http://example.com/?s=search_phrase to http://example.com/s?s=search_phrase.