【问题标题】:Apache RewriteRule allow blank after slash or specified valuesApache RewriteRule 允许在斜线或指定值后留空
【发布时间】:2020-04-15 20:50:28
【问题描述】:

我需要有关以下 Apache RewriteRule 的帮助

RewriteRule ^(customers)/(active|create)/?$ /mod/customers/?type=$2 [NC,L]

此规则仅适用于/ 之后的内容,例如:http://example.com/customers/active

如果url是http://example.com/customers就不行

这个 RewriteRule 怎么写才能让http://example.com/customershttp://example.com/customers/active 一样工作

/customers 后跟什么都没有,或/customers 后跟/active/create

【问题讨论】:

  • http://example.com/customers/http://example.com/customers/active/ 怎么样?
  • 你的意思是尾随的/
  • 是的,是否允许?
  • 当前网址中没有尾随/...

标签: regex apache mod-rewrite url-rewriting


【解决方案1】:

你可以使用这个正则表达式:

^(customers)(?:/(active|create))?/?$

它使用可选的非捕获组来允许 URL,例如 http://example.com/customershttp://example.com/customers/active。 `active|create 仍被捕获在第 2 组中。

Demo on regex101

此正则表达式允许在 URL 上使用尾随 /,例如http://example.com/customers/http://example.com/customers/active/。如果不需要,只需删除$ 前面的/?,即

^(customers)(?:/(active|create))?$

Demo on regex101

【讨论】:

  • 这很好用。如果我需要 active 后跟 10 到 20 个字符之间的字母和数字,我将如何将其添加到上述规则中? Eg:example.com/customers/active/a1dx12s5e4jklo
  • @Norman 也许是regex101.com/r/aW2QL9/3?允许activeactive 后跟/ 和10-20 个字符。如果您必须有字符,请删除(/[a-z]{10,20} 组之后的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-05
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
相关资源
最近更新 更多