导航首页 » 文章首页 » 站长技术 » Apache Rewrite解决问号匹配的写法?RewriteCond判断QUERY_STRING为空的写法?

Apache Rewrite解决问号匹配的写法?RewriteCond判断QUERY_STRING为空的写法?

2022-11-10 300 站长技术

ApacheRewrite处理?问号后的请求参数

A地址:http://www。domain。com/ProductView.jsp?lClassID=200
B地址:http://www。domain。com/goods.php?id=3

实现把用户输A地址跳到B地址,就是跳转的功能。

原先用我用最常的方法实现如:RewriteRule ^ProductView.jsp?lClassID=200$ goods.php?id=3 [L] 看上去是没有问题的,但在地址上输入跳转不了。

后来网上查了一下资料如下:


规则:

文本

. 任意一个单字符

[chars] 字符类: "chars"中的任意一个字符

[^chars] 字符类: 不在"chars"中的字符

text1|text2 选择: text1 或 text2


量词

? 前面的字符出现 0 或 1 次

* 前面的字符出现 0 或 N 次(N > 0)

+ 前面的字符出现 1 或 N 次(N > 1


原来这样:?号把前面的p也作为参数了,p?(\?)就变成了$1,当在地址中输入http://www.iermei.com/ProductView.jslClassID=200 可实现跳转,但这显然不是需求那样的.


本来都想放弃用重写了,在网上又找了一下终于找到了,功夫不负有心人啊,

解决方法如下:

RewriteCond %{QUERY_STRING} ^lClassID=200$

RewriteRule ^ProductView\.jsp$ goods\.php\?id=3 [L]

我找到的相关资料:

把 /abc?id=123 => /def.php?id=123 的写法:

RewriteEngine on

RewriteCond %{QUERY_STRING} ^id=(.+)$

RewriteRule ^/abc$ /def.php?sid=%1 [L]

RewriteRule 不会去匹配URL中?(问号)后面的字符串,需要用RewriteCond来匹配


说明:

RewriteRule Pattern 在匹配时候不会对问号后面的查询字符进行处理,需要用一个%{QUERY_STRING}变量的RewriteCond指令。


需要主意的问题:

1、在新地址/sell/list-%1.html中需要使用%加序号来取得RewriteCond配置中的对应参数内容,而不是通常$(匹配RewriteRule中的内容)

2、新地址/sell/list-%1.html?中需要在尾部加上一个问号来终结查询字符串,否则会出现/sell/list-1000.html?cid=1000的情况。

==========================================

PS.上面整篇内容迷迷糊糊,这里再附个说到点子上的例子出来:

RewriteEngine OnRewriteBase /

RewriteCond %{QUERY_STRING} ^$

RewriteRule ^(.*)$ index.php?path=$1 [L,NE]


RewriteCond %{QUERY_STRING} !^$

RewriteRule ^(.*)$ index.php?path=/$1\?%{query_string} [L,NE]

这个例子用到两个条件,即是有条件执行重写,第一条件是当URL没有参数,即?问号后面没有内容时,执行重写并结束匹配;第二个条件反过来了,就是URL的“?”号后面带着参数,然后重写时把问号后面的也传递过去(这里是重点!)。

RewriteEngine On
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^topic-(.+)\.html$ portal.php?mod=topic&topic=$1&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^article-([0-9]+)-([0-9]+)\.html$ portal.php?mod=view&aid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^forum-(\w+)-([0-9]+)\.html$ forum.php?mod=forumdisplay&fid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^tid=([0-9]+)$
RewriteRule ^read.php$ forum.php?mod=viewthread&tid=$1&extra=page%3D1&page=1 [QSA]
RewriteCond %{QUERY_STRING} ^tid=([0-9]+)&page=([0-9]*)$
RewriteRule ^read.php$ forum.php?mod=viewthread&tid=$1&extra=page%3D1&page=$2 [QSA]
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ forum.php?mod=viewthread&tid=$1&extra=page\%3D$3&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^group-([0-9]+)-([0-9]+)\.html$ forum.php?mod=group&fid=$1&page=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^space-(username|uid)-(.+)\.html$ home.php?mod=space&$1=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^blog-([0-9]+)-([0-9]+)\.html$ home.php?mod=space&uid=$1&do=blog&id=$2&%1
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^archiver/(fid|tid)-([0-9]+)\.html$ archiver/index.php?action=$1&value=$2&%1
上一篇
764

cPanel自定义401错误页面“未显示""不生效"