How can I match query string variables with mod_rewrite?
RewriteCond %{QUERY_STRING} book=(\w+)&page=(\d+)
RewriteRule ^index.php /%1/%2? [L,R=301]
Because RewriteRule only looks at the path (up to but not including the question mark), use RewriteCond to capture the values in the query string.
Note that the matches from RewriteCond
are captured in %1
,
%2
, etc., rather than $1
, $2
, etc.
Also note the ?
at the end of RewriteRule
. It tells mod_rewrite
not to append the original query string to the new URL, so you end up with
/DesignPatterns/151
intead of
/DesignPatterns/151?book=DesignPatterns&page=151
.
The [L,R=301]
flags do two things:
-
L
ensures that no other rules that might otherwise match will be processed (in other words, it ensures this is the "last" rule processed). -
R=301
causes the server to send back a redirect response. Instead of rewriting, it tells the client to try again with the new URL. The=301
makes it a permanent redirect, so that, among other things, search engines will know to replace the old URL with the new URL in their indexes.
Related videos on Youtube
Cédric Guillemette
At the stage in my career where I tend to focus more on people than code. I still use Stack Overflow every day, but I'm more likely to be active on Twitter (@patrick_mc) or GitHub. As moderator for its first year, I helped get ux.stackexchange.com off the ground. Favorite Books for Programmers Clean Code by Robert C. Martin The Pragmatic Programmer by Hunt & Thomas Working Effectively With Legacy Code by Michael Feathers Refactoring by Martin Fowler The Inmates are Running the Asylum by Alan Cooper
Updated on April 10, 2020Comments
-
Cédric Guillemette about 4 years
Suppose I have URLs with query string parameters like these:
/index.php?book=DesignPatterns&page=139 /index.php?book=Refactoring&page=285
Using mod_rewrite, how can I redirect them to SES URLs like these?
/DesignPatterns/139 /Refactoring/285
-
TheJosh almost 11 yearsYou probably also want the [L] flag when you have multiple rewrite rules. The [L] flag stops processing after the rule has matched, and the [R] flag DOES NOT implicitly include it.
-
keithwyland over 9 yearsThe $ vs % were killing me. I had no idea. Thank you!
-
Uzair Farooq over 8 yearsTo not append the original query string to the new url use
[QSD]
flag (httpd.apache.org/docs/2.4/rewrite/flags.html#flag_qsd) -
Luciano almost 8 yearsAnswers like this make me wish I could star them for later easy finding. Instead I end up starring the question.
-
ahnbizcad almost 8 years@Luciano just recognize it by upvoting the answer on a question you starred.
-
ahnbizcad almost 8 yearsisn't this invalid? you'd need to escape the dot in
^index.php
with^index\.php
-
fpilee over 6 yearsI spend like 4 hours debugging :D until I googled and I discovered that mod rewrite doesn't match the query string