Last Updated on April 21, 2021 by Amit
Rewriting a complax URL using htaccess
In this post I will show you how to rewrite a long URL that has multiple query string perameters.
This two minutes read post is for beginners who wish to learn Apache URL rewriting.
We will convert the following URL :
Our original URL http://example.com/user.php?name=foobar&location=somewhere&id=123 contains three query string perameters name , location and id. The URL is long, hard to remember and not search engine friendly .
It needs to be converted into a clean format so that it can easily be indexed by search engines.
The new URL http://example.com/user/foobar/somewhere/123 is short , easier to remember and search engine friendly. It contains 4 path segments user , foobar , somewhere and 123 each points to the query string except the first one user as its there just for naming purpose.
Here is the rule we can use to convert our complex URL into short one
RewriteEngine on RewriteRule ^user/foobar/somewhere/123$ /user.php?name=foobar&location=somewhere&id=123 [L]
The above rule create the short URL. It allows you to access the original query string URL using the new short URL. If you visit example.com/user/foobar/somewhere/123 the rule will internally map the URL to the original query string URL.
The rule above applies to a single Query string URL or static path. If the URL is dynamic you can use Regular expression based pattern instead of the static pattern.
RewriteEngine on RewriteRule ^user/(.+)/(.+)/(.+)$ /user.php?name=$1&location=$2&id=$3 [L]
The regular expression pattern ^user/(.+)/(.+)/(.+)$ matches any URL path string starting with user followed by /name/location/id . The pattern matches /user/name/location/id . The $n variables reffers to the match in capture group (.+) where $1 is the match from the first group.
You can manually modify the rule if your URL has more then three perameters . For example if your original URL has 4 query perameters then you can add an additional capture group to the pattern and link the match to the destination path using $4 variable.
I hope you enjoyed reading this post. Thank you.