Skip to content
Home » Web » Apache » Rewrite Query String into Plain URL

Rewrite Query String into Plain URL

As you may already know that URLs are always the shorter the better for both visitors and search engines to understand your web pages at a glance. Therefore, the plain URLs should be better than the URLs with a long query string.

For example, we would like the directory-based URL:

http://www.example/travel/tools/backpacks

to replace the long dynamic parameters:

http://www.example/products.php?class=travel&subclass=tools&name=backpacks

In such case, we can use Apache Rewrite to implement the plain URL by modifying /etc/httpd/conf/http.conf.

[root@test ~]# vi /etc/httpd/conf/httpd.conf
...
    RewriteEngine On
    RewriteCond %{QUERY_STRING} ^$  # Without any query string
    RewriteRule ^(.+)/(.+)/(.+)/?$ products.php?class=$1&subclass=$2&name=$3 [B,NC,L]
...

In another words, we use the dynamic page in the background:

products.php?class=$1&subclass=$2&name=$3

To process the URI pattern:

^(.+)/(.+)/(.+)/?$

As you can see, there's no any query string and looks more like a natural string in the foreground.

Please test your web pages after restarting Apache httpd. For more syntax and examples, you may refer to the documentation:

  1. Apache mod_rewrite Introduction - Apache HTTP Server Version 2.2
  2. RewriteRule Flags - Apache HTTP Server Version 2.2

Leave a Reply

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