mod_rewrite:用破折号替换下划线 [英] mod_rewrite: replace underscores with dashes

查看:101
本文介绍了mod_rewrite:用破折号替换下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里透露了我对REGEX-fu的尴尬无知,但是:我目前有一个网站,其中大量文章的URL都写为"article_name",而较新的URL则写为"article-name"

I'm revealing my embarrassing ignorance of REGEX-fu here, but: I currently have a website where a load of the articles' URLs are written as "article_name", whilst the newer ones are written as "article-name".

我想将它们全部都使用破折号,所以是否可以使用正则表达式将较旧的URL重写为较新的URL?

I want to move all of them to using dashes, so is there a regular expression I could use to rewrite the older URLs to their newer equivalents?

先谢谢您!

推荐答案

首先,您必须在现有URL中实现一致性.基本上,您必须规范化所有现有名称才能始终使用破折号.好的,您已经完成了.

First you must achieve consistency in the existing URLs. Basically, you have to normalize all existing names to always use dashes. Ok, you've done that.

我们从以下假设开始:

URL大致采用以下格式:

The URL is roughly of the form:


http://example.com/articles/what-ever/really-doesnt_matter/faulty_article_name

,其中仅应重写/articles下的URL,并且仅需要清洁/faulty_article_name部分.

where only URLs under /articles should be rewritten, and only the /faulty_article_name part needs to be sanitized.

对于Apache:

RewriteEngine     On
RewriteRule       ^(/?articles/.*/[^/]*?)_([^/]*?_[^/]*)$ $1-$2 [N]
RewriteRule       ^(/?articles/.*/[^/]*?)_([^/_]*)$       $1-$2 [R=301]

这通常是受到GApple回答的启发.

That's generally inspired by GApple's answer.

第一个/?确保此代码将同时在vhost confs和.htaccess文件上运行.后者不希望出现斜线.

The first /? ensures that this code will run on both vhost confs and .htaccess files. The latter does not expect a leading slash.

然后我添加articles/部分,以确保规则仅适用于/articles内的URL.

I then add the articles/ part to ensure that the rules only apply for URLs within /articles.

然后,尽管URL中至少有两个下划线,但我们仍在循环浏览规则.当我们最后只剩下一个下划线时,第二条规则开始执行,将其替换为破折号,然后执行永久重定向.

Then, while we have at least two underscores in the URL, we keep looping through the rules. When we end up with only one remaining underscore, the second rule kicks in, replaces it with a dash, and does a permanent redirect.

Ph.

这篇关于mod_rewrite:用破折号替换下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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