需求:

将 host/item.html?type=test
rewrite 成
host/?q=item&type=test
其中 item 和 test 是可变的,并且 ?type=test 可有可无。

解决:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/[^/]+\.html$
RewriteCond %{QUERY_STRING} ^(type=.*)?$
RewriteRule ^([^/]+)\.html$ /?q=$1&%1 [L]
</IfModule>

解释:

  1. ?type=test 是不会出现在 REQUEST_URI 里的,必须使用 QUERY_STRING 来获得它。
  2. 若有多个 RewriteCond,只能反向引用最后一个 RewriteCond 里的 pattern 的 group。
  3. RewriteRule 后面的 pattern 是用来匹配当前 URL 的,当前 URL 不是 REQUEST_URI。因为(因此?)它会比 REQUEST_URI 少一个前导斜杠 "/",并且它可能已经被前面的 RewriteRule 改变过。

规则 BT 吧?第一个搞得我差点以为无解,第三个规则也消耗了我大量时间。本以为不用测试就能搞定的一个小问题居然花了 40 分钟左右才完成。-_-b

Tags: , ,