RewriteCond RewriteRule for .htaccess based on URL

2019-09-09 01:01发布

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

2条回答
We Are One
2楼-- · 2019-09-09 01:34

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]
查看更多
孤傲高冷的网名
3楼-- · 2019-09-09 01:37

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.

查看更多
登录 后发表回答