【问题标题】:.htaccess complex rewrite rule.htaccess 复杂的重写规则
【发布时间】:2019-08-09 21:37:54
【问题描述】:

我有一个有点复杂的重写规则,我无法掌握它。

我想做的是使用 .htaccess 让我的网站看到这个链接:

https://some-domain.com/human/jeff

作为这个链接(因为系统知道如何处理这个链接):

https://some-domain.com/?type=human&which=jeff

注意事项:

  1. 我只想在type=human 时应用此规则。
  2. which 参数只能包含字母字符。
  3. 如果类型是人类,那么除了这些之外,不会有更多的 url 参数。

经过大量尝试,这是我最终失败的 .htaccess 内容:

RewriteEngine On    
RewriteRule     ^(https://[^/]+)/?\?type=(human)&which=([a-zA-z]+)$ $1/$2/$3 [NC, L]

这是它背后的逻辑:

  • 第 1 组:(https://[^/]+) $1 将包含匹配 https://{any non empty string that does not containing "/"} - https://some-domain.com 的任何字符串
  • 静态:/?\? 匹配“/?”或“?”
  • 第 2 组:type=(human) $2 将包含“人类”
  • 第 3 组:which=([a-zA-z]+) $3 将包含一个只有字母字符的非空字符串 (jeff)。

预期结果:
这将匹配正则表达式

https://{any non empty string that does not containing "/"}/human/{any non empty string}

我几乎被困在这里

谢谢!

编辑:
我还应该提到,重写应该只针对 POST 请求,并且需要 post 参数。

【问题讨论】:

  • 您在重写模式中使用了无效字符。 httpdomainquerystring 有不同的东西在 RewriteRule 中无法匹配。您需要使用RewriteCond 指令。不知道下面的答案对您有用。
  • @starkeen 实际上我错了,它没有用。你能帮我遵守规则吗?

标签: regex apache .htaccess url-rewriting


【解决方案1】:

感谢 Michał Turczyn 和 Mohammed Elhag 的帮助。
这是 .htaccess 的最终和工作内容。

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_URI} ^/(human)/([a-zA-Z]+)/?$ [NC]
 RewriteRule ^(human)/(.*)$ /?type=$1&which=$2 [L]
</IfModule>

此规则仅适用于 REQUEST_URI 为 /human/{任何非空字符串}

【讨论】:

    【解决方案2】:

    在这一行:

    RewriteRule     ^(https://[^/]+)/?\?type=(human)&which=([a-zA-z]+)$ $1/$2/$3 [NC, L]
    

    这部分 ^(https://[^/]+)/?\?type=(human)&amp;which=([a-zA-z]+)$ 是 pattren,应该匹配 URI 但不是完整的 URL

    试试这个:

    RewriteEngine On
    RewriteCond %{QUERY_STRING} ^type=(human)&which=([A-Za-z]+)$  [NC]
    RewriteRule ^ /%1/%2? [R=301,L]
    RewriteRule ^(human)/(.*)$ /?type=$1&which=$2 [L]
    

    注意:清除浏览器缓存然后测试。

    【讨论】:

    • TY Mohammed,你能解释一下这句话吗? RewriteRule ^ /%1/%2? [R=301,L]
    • @HikeNalbandyan 这是 RewriteRule 所以,模式(正则表达式) ^ 匹配任何事物,然后替换(目标)%1 代表先前条件(人类)中的第一个捕获组,%2 代表第二个捕获组([A-Za-z])
    【解决方案3】:

    试试这个模式:^(https?:\/\/[^\/]+\/)\?type=(human)&amp;which=([a-z]+)$

    ^ - 字符串的开头

    https?:\/\/[^\/]+\/ - 匹配http 字面意思,然后匹配s 可选(零或一),\/\/ 字面意思匹配//[^\/]+ 匹配除/ 之外的一个或多个字符,然后匹配/ 字面意思

    \?type=(human)&amp;which=([a-z]+) - 匹配?,然后匹配type=humanhuman 将存储在捕获组中),然后匹配&amp;which=,然后匹配一个或多个字母与[a-z]

    p>

    当它是期望的形式(type=human 并且只有which 中的字母)时,它将匹配您的字符串。

    替换模式:\1\2\/\3

    \1 - 替换为第一个捕获组,类似于 \2\3

    Demo

    【讨论】:

    • 这是你的意思吗? RewriteRule ^(https?:\/\/[^\/]+\/)\?type=(human)&amp;which=([a-z]+)$ \1\2\/\3
    • @HikeNalbandyan 是的,但我认为您需要使用$1 而不是\1。试试看:)
    猜你喜欢
    • 1970-01-01
    • 2011-12-21
    • 2010-12-07
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多