htaccess 用正则表达式重写规则 [英] htaccess rewrite rule with regular expression

查看:27
本文介绍了htaccess 用正则表达式重写规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难使用旧 URL 的一部分为重定向创建重写规则.示例:

I have a hard time to create rewrite rule for a redirect using part of an old URL. Example:

旧网址:http://www.example.com/news/index.php/2014/11/07/my-blog-post-from-old-site或者http://www.example.com/news/index.php/2014/11/07/my_blog_post_from_old_site

新网址:http://www.example.com/2014/11/07/my-博客帖子

从破折号中删除后,新 URL 应该只有日期和永久链接的前三个元素.即使我不确定是否可以使用 .htaccess 规则来完成,但肯定可以使用 PHP 来完成.

New URL should to have only dates and first three elements of a permalink after stripping from dashes. Even I'm not sure if can be done using .htaccess rule but for sure can be done using PHP.

这是我的 .httaccess 规则

Here are my .httaccess rules

RewriteCond %{HTTP_HOST} ^example.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(/?news/index.php/.*/[^/]*?)_([^/]*?_[^/]*)$ $1-$2 [N]
RewriteRule ^(/?news/index.php/.*/[^/]*?)_([^/_]*)$ $1-$2 [R=301]
RewriteRule ^news/index.php/([^/]+)-([^/]+)-(.*)$ http://www.example.com/$1-$2-$3 [L,R=301,NC]

推荐答案

只匹配块,直到遇到连字符 (-):

Just match for the blocks until hyphen (-) is encountered:

RewriteRule ^news/index.php/([^-]+-[^-]+-[^-]+).* /$1 [R=301,L,NC]

这篇关于htaccess 用正则表达式重写规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆