Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

regex - How can I match query string variables with mod_rewrite?

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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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:

  1. L ensures that no other rules that might otherwise match will be processed (in other words, it ensures this is the "last" rule processed).
  2. 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...