5.20. Rewriting Elements between Path and Query String
Problem
You want to turn portions of a URL into query-string parameters, or vice versa.
Solution
To rewrite http://example.com/path/to/5 to http://example.com/path/to?id=5:
RewriteRule "^(/path/to)/(\d+)" "$1?id=$2" [PT]
To go the other way:
RewriteCond "%{QUERY_STRING}" "\bid=(\d+)\b"
RewriteRule "(/path/to)" "$1/%2" [PT,QSA]Tip
Note that the arguments to the RewriteRule directives need to be structured differently if they occur in a .htaccess file. The above solution illustrates the syntax if they’re put into the server-wide configuration files.
Discussion
It is quite common for sites to have to change the way URLs are structured, either moving portions into or out of the query-string portion. This often becomed necessary when the underlying software is changed—say, from one blogging package to another. The new software requires URLs to be in a different format, but you don’t want to invalidate all the old-style URLs that might be bookmarked or otherwise spread around the Web.
This is a perfect application for mod_rewrite, and quite simple to accomplish as well, as demonstrated in the solution.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access