Mod_rewrite处理“数据格式”参数


Mod_rewrite to handle "data format" parameter

我的示例htaccess文件包含代码:

RewriteRule ^cart$ index.php?controller=cart&action=default [L,NC]
RewriteRule ^listing$ index.php?controller=product&action=listing [L,NC]
RewriteRule ^blog$ index.php?controller=blog&action=listing [L,NC]

我可以通过 example.com/cart 访问购物车

我的问题:是否有可能添加一些额外的参数,例如"数据格式"参数?

我想访问 example.com/cart(作为 html 输出)和 example.com/cart.xml和其他网址:example.com/listing.xmlexample.com/blog.xml

对我来说重要的是不要修改每个重写规则。我的htaccess文件中有数百行,因此添加一些修改URL请求的代码会快得多。

它可以这样工作:

  1. 从网址中移除.xml
  2. 匹配重写网址
  3. 添加 ?format=xml (index.php?controller=blog&action=listing&format=XML)

现代PHP和非PHP框架通常使用此功能将渲染的网站输出为html,xml,json等。

@EDIT:

谢谢!我应该像你写的那样使用QSA标志。

我现在用来添加.xml参数的规则:

RewriteRule ^(.*).xml$ $1?params[output_format]=xml
您可以使用

以下规则:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}'s/+(cart|listing|blog)'.(xml)'s [NC]
RewriteRule ^ /%1?format=%1 [R=302,L]
RewriteRule ^cart$ index.php?controller=cart&action=default [L,NC,QSA]
RewriteRule ^listing$ index.php?controller=product&action=listing [L,NC,QSA]
RewriteRule ^blog$ index.php?controller=blog&action=listing [L,NC,QSA]
  • 第一条规则将从 URL 中删除.xml并向其添加?format=xml查询参数。
  • 带有 QSA 标志的第二条规则添加剩余的查询参数。