doudou0111
doudou0111
2017-08-03 16:22

正则表达式在查询参数上匹配一个单词n次,以便与rewritecond .htaccess文件一起使用

  • regex
  • wordpress
  • php

I would like some help please. I would like to match a condition from the http referer in the htaccess file within a wordpress website. I want to pass a query parameter from the 'referer' to the request uri

I'm trying to use the mod_rewrite function to do this

RewriteCond %{HTTP_REFERER} ^((?!menu=a.*\&menu=a).)*$ 
RewriteRule ^.*$ %{REQUEST_URI} [L,QSA]

I want to match the following

http://example.co.uk?menu=a&menu=a false
http://couldbeanything.co.uk?couldbeanything=b&menu=a true
http://example.co.uk?tile=b&menu=a true
http://example.co.uk/?menu=a true
http://example.co.uk/?menu false
http://example.co.uk/testing123/?tile=a&menu=a true
http://example.co.uk false
http://example.co.uk/?p=12 false
http://example.co.uk/?p=12&menu=a&menu=a false
http://example.co.uk/?p=12&menu=a&tile=b&menu=a false

I want to be able to match on the query parameter when it occurs once and once only. I dont want to match on zero occurrences. I do not want to match on two or more occurrences.

I have tried

^((?!menu=a.*\&menu=a).)*$

I have tried

.*?.*(menu=){1}

I have tried

^(?!.*menu=.*menu=).+$

I have tried

^(?!(.*menu=){1})(.*menu=){1}.*$

All of the above are not quite exactly what I need. I have tried a lot of different regexs.

I thought I could try and inversing matching which I saw in another post and then somehow manipulating this in the htaccess so i tried this but couldn't match properly either.

^((?!menu).)*$

I feel like I might be approaching this from the wrong angle and this might not be what regex is for.

Maybe I could do a count matching on menu=somevariable and manipulate that from the htaccess file? I couldn't find information on google search how to do this.

Any input on how to solve this would be much appreciated. I dont mind if it's not in regex as long as it's doable in the htaccess file.

Thanks for any input.

Further Update after finding correct regex

I have tried this but I'm getting erratic behaviour from the site as the query is added repeatedly to the request uri.

RewriteCond %{REQUEST_URI} ^(?!.*(menu=)).*$
RewriteCond %{HTTP_REFERER} ^(?!.*\menu=\b.*\bmenu=\b).*\bmenu=\b.*$
RewriteRule ^.*$ %{REQUEST_URI}?menu=a [QSA]
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答