【问题标题】:htaccess RewriteRule regexhtaccess RewriteRule 正则表达式
【发布时间】:2018-01-08 19:00:50
【问题描述】:

我有数百个这样的旧链接需要重定向。

这是一个例子:

/index.php?option=com_content&view=article&id=433:seventh-character-code-categories-and-icd-10-cm&Itemid=101&showall=1

/seventh-character-code-categories-and-icd-10-cm

基本上我需要删除 /index.php?option=com_content&view=article&id=433: 部分。

我试过这个,但我对 [0-9] 和 : 部分感到困惑,所以以下内容不起作用:

RewriteRule ^/index.php?option=com_content&view=article&id=[0-9]:(.*)$ /$1 [L,R=301]

【问题讨论】:

标签: regex .htaccess redirect


【解决方案1】:

假设您要在您提到的查询字符串中从: 之后到& 之前捕获,然后尝试这个表达式:

^[^\:]*\:([^\&]*)\&.*$

正如 @starkeen 在 cmets 中提到的,您必须检查 查询字符串。这可以使用RewriteCond %{QUERY_STRING}来完成

所以如果index.php 在根文件夹中:

RewriteEngine On
RewriteCond %{REQUEST_URI}  ^\/index\.php$
RewriteCond %{QUERY_STRING} ^[^\:]*\:([^\&]*)\&.*$
RewriteRule ^(.*)$ http://example.com/%1 [R=301,L]

这是另一个例子。这是一个子文件夹:

RewriteEngine On
RewriteCond %{REQUEST_URI}  ^\/pages\/index\.php$
RewriteCond %{QUERY_STRING} ^[^\:]*\:([^\&]*)\&.*$
RewriteRule ^(.*)$ /pages/%1? [R=301,L]

另外,请注意 url /pages/%1? 末尾的 ?,这可以防止重新附加查询字符串。

另外,由于在 RewriteCond 中设置,捕获的组将设置为变量 %{number}

顺便说一句,根据你的服务器配置,你可能需要添加 NE 标志,比如[NE,L,R=301] 加测试是否需要对文字字符进行双重转义。

【讨论】:

  • 你为什么要使用第一个&符号?我们在乎它之前的一切,不在乎包含它之后是什么
  • 这将不起作用,因为您正在匹配 RewriteRule 模式中的 url 查询字符串。
  • 我更新了答案。我之前没有注意你的 .htaccess 结构。也许这会有所帮助。
【解决方案2】:

什么是直接方法。跳过所有直到分号,马赫字符串直到 & 并用 first much 替换所有

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{QUERY_STRING} [^:]+:([\w-]+[^&]).*
    RewriteRule .*$ \/%1?  [R=301,L]  

</IfModule> 

【讨论】:

  • 查询字符串不是 RewriteRule 指令匹配的一部分。您必须使用 RewriteCond 分别使用 % {QUERY_STRING} 变量捕获查询字符串
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多