RewriteCond RewriteRule for .htaccess based on URL to a new page, regular expression

元气小坏坏 提交于 2019-12-25 00:28:26

问题


I have an interesting RewriteRule and I am not sure to make the regular expression.

In short I would like to examine the URL after the second / - based on the contents, possibly forward.

It sums down to these two rules:

  1. Redirect if string after second / contains any letter
  2. Redirect if string after second / is longer than 7 characters

Here are examples:

http://www.mysite.org/section/subsection/2011 (OK, do nothing)

http://www.mysite.org/section/subsection/2011-11 (OK, do nothing)

http://www.mysite.org/section/subsection/2011-11-09 (NOT OK, redirect)

http://www.mysite.org/section/subsection/2011-11-W1 (NOT OK, redirect)

Please help me with the Rewrite Rule and Rewrite Cond


回答1:


I based the following regex off of your examples which seemed to analyze everything after the last '/' instead of the second.

/[^A-Za-z]{1,7}$

In plain English, this regex matches a group of characters that follows a '/' and contains 1-7 non-alphabetical characters. To make it only match the last '/' I appended a '$', which matches the end of a line.

Also, since you are dealing with URLs you might want to add "/?" before the '$' in case there is a dangling '/' at the end.

/[^A-Za-z]{1,7}/?$

I hope this answers your question.




回答2:


As Lane Aasen points out, your examples and rules don't match up. I'm taking your examples to mean that the rules should apply to the 3rd path segment, and suggest the following. You don't say whether the redirect destination is different or not depending which rule matches. I've taken it to be different.

RewriteEngine on
# redirect if any letter is contained in 3rd part of path
RewriteRule ^([^/]+/){2}.*[a-zA-Z] http://www.bbc.co.uk [R=permanent,L]
# redirect if there are more than 7 characters in 3rd part of the path
RewriteRule ^([^/]+/){2}.{7,} http://www.ibm.com [R=permanent,L]


来源:https://stackoverflow.com/questions/8043310/rewritecond-rewriterule-for-htaccess-based-on-url-to-a-new-page-regular-expres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!