使用 .htaccess 中选定的查询字符串参数重写 URL [英] Rewriting URL with selected query string parameters in .htaccess

查看:28
本文介绍了使用 .htaccess 中选定的查询字符串参数重写 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近更改了我的 CMS,并且想要重写我的一些 URL 以匹配新的 URL/查询字符串参数格式.

旧网址是:

http://www.mysite.com/search.cgi?tag=foo&blog_id=bar&other=baz

新网址应为:

http://www.mysite.com/?s=foo

换句话说,旧格式中有几个查询字符串参数,但我只关心将 tag 参数重写为 s 并保持相同的值.其他参数应该被丢弃.当然,参数的顺序应该无关紧要.标签是否是唯一的参数也不重要.

有什么想法吗?

解决方案

如果您的服务器支持,您可以尝试使用正则表达式和分组.如果我没记错你只需要重写一个参数,我想你可以尝试类似的东西(如果你使用带有 mod_rewrite 的 apache):

<前>RewriteCond %{QUERY_STRING} ^.*(\btag\b=(\w+|&\w+;)+)重写规则 ^(.+)/$1?%1 [L]

我稍微改进了正则表达式以匹配标签",无论它在查询字符串中的位置如何,并保留特殊字符序列,例如 &amp; 此外,它应该避免与相似参数的匹配(即:它不会匹配名为alttag"的参数).

编辑 #2: 另一种方法(尤其是当您必须过滤多个参数时)是使用外部程序进行重写.本页:http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritemap(特别是外部重写程序"部分)包含有用的信息.

I recently changed my CMS, and want to rewrite some of my URLs to match the new URL/query string parameter format.

The old URL was:

http://www.mysite.com/search.cgi?tag=foo&blog_id=bar&other=baz

The new URL should be:

http://www.mysite.com/?s=foo

In other words, there were several query string parameters in the old format, but I only care to rewrite the tag param to s while keeping the same value. The other parameters should be discarded. Of course the order of the parameters shouldn't matter. It also shouldn't matter whether tag is the only parameter or not.

Any ideas?

解决方案

You can try to use regular expression and grouping, if your server supports that. If I am not mistaken you have to rewrite only one parameter, I guess you could try something like (if you are using apache with mod_rewrite):

RewriteCond %{QUERY_STRING} ^.*(\btag\b=(\w+|&\w+;)+)
RewriteRule ^(.+) /$1?%1 [L]

Edit: I improved the regular expression a little bit to match "tag" regardless of its position in the query string and to preserve special characters sequences such as &amp; In addition it should avoid matches with similar parameters (i.e.: it wouldn't match a parameter called "alttag").

Edit #2: An alternative (especially if you have to filter several parameters) is to use an external program to do the rewrite. This page: http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritemap (in particular the section "External rewriting program") contains useful information.

这篇关于使用 .htaccess 中选定的查询字符串参数重写 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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