我怎样才能查询字符串变量与mod_rewrite的匹配吗? [英] How can I match query string variables with mod_rewrite?

查看:112
本文介绍了我怎样才能查询字符串变量与mod_rewrite的匹配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有查询字符串参数,如以下网址:

  /index.php?book=DesignPatterns&page=139
/index.php?book=Refactoring&page=285

使用 mod_rewrite的,我该怎么重定向到SES网址,这样的?

  / DesignPatterns / 139
/重构/ 285


解决方案

 的RewriteCond%{QUERY_STRING}书=(\\ w +)及网页=(\\ D +)
重写规则^的index.php / 1%/ 2%? [L,R = 301]

由于重写规则只着眼于路径(最多但不包括问号),使用的RewriteCond 捕捉值在查询字符串

请注意,从的RewriteCond 比赛中被捕获%1
%2 等,而不是 $ 1 $ 2 等。

另外要注意的重写规则的结束。它讲述了mod_rewrite
不追加原来的查询字符串到新的URL,那么你最终
/ DesignPatterns / 151 这一翻译的
/ DesignPatterns / 151 =书&De​​signPatterns放大器;?页= 151

[L,R = 301] 标记做两件事情:


  1. 确保,否则可能会比赛将不处理任何其他规则(换句话说,它保证这是最后规则处理)。

  2. R = 301 导致服务器发回一个重定向响应。
    相反重写,它告诉客户端新再试一次
    URL。在 = 301 使它成为一个永久重定向,这样一来,除其他事项外,搜索引擎会知道在他们的指数新的URL,以取代旧的URL。

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

解决方案

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.

这篇关于我怎样才能查询字符串变量与mod_rewrite的匹配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆