开发者

Append a parameter to a querystring with mod_rewrite

I would like to use mod_rewrite to append a parameter to the end of a querystring. I understand that I can do this using the [QSA] flag.

However, I would like the parameter appended ONLY if it does not already exist in the querystring. So, if the querystring was:

http://www.mysite.com/script.php?colour=red&size=large

I would like the above URL to be re-directed to

http://www.mysite.com/script.php?colour=red&size=large&weight=heavy

Where weight=heavy开发者_StackOverflow中文版 is appended to the end of the querystring only if this specific parameter was not there in the first place! If the specific parameter is already in the URL then no redirect is required.

Can anybody please suggest code to put in my .htacess file that can do this?


EDIT: tested and modified it, now it works for me

I assume you want to add a default weight parameter if there is no weight at all:

RewriteEngine on
RewriteBase /
RewriteCond %{QUERY_STRING} !weight=
RewriteRule ^script.php     script.php?weight=heavy [R,L,QSA]

This is esentially the same what @coreyward answered, but a bit more specific. (R flag, to make the change visible, and the weight parameter does not have to be heavy.)

Hope this helps!


This is a really strange thing to do. It's as though you're setting a default for your system, which is a pretty standard thing to do. The problem is that it's unmaintainable and awkward to be setting that default in your VHost definition or .htaccess file where you're literally configuring Apache.

I advise against doing it this way, but this is a quick and dirty way to do what you're looking for:

RewriteCond %{QUERY_STRING} !weight=heavy
RewriteRule /script.php /script.php?weight=heavy [QSA]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜