htaccess用连字符递归替换下划线 [英] Htaccess recursively replace underscores with hyphens

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

问题描述

我正在尝试将所有带下划线的URL重定向到相同的URL,但下划线被连字符替换。

I'm trying to redirect all URLs with underscores to the same URL but with underscores replaced by hyphens.

我已经在线尝试了许多示例,但是这些示例都提供了服务器错误或似乎导致服务器崩溃的循环。

I've tried many examples online but these either provide server errors or seem to result in a loop that crashes my server.

根据我的阅读,以下内容应该可以工作:

From what I've read the following should work:

RewriteRule ^([^_]*)_([^_]*_.*) $1-$2 [N]
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,R=301]

OR

RewriteRule ^(.*)_(.*)$ $1-$2 [N,E=redirect:true]
RewriteCond %{ENV:redirect} ^true$
RewriteRule (.*) $1 [R=301]

但是这些却没有,相反,它们似乎导致页面加载一段时间,然后超时/ 404。

However these do not, instead they seem to cause pages to load for a while and then timeout / 404.

我需要重定向的一些示例URL如下:

Some example URLs that I need to redirect are as follows:

https://domain.com/blog/this_is_a_post_5
https://domain.com/blog/i_am_a_post_12
https://domain.com/forum/i_am_a_forum_post_15

如何在尽可能少的规则中用下划线替换下划线? p>

How can I replace the underscores with hyphens in the above in as few rules as possible?

推荐答案

由于默认值<$,如果用连字符替换下划线超过10个,则其中一种实现将导致500内部错误。 c $ c> LimitInternalRecursion 变量为10。

One of these implementations will cause 500 internal error if there are more than 10 underscores to be replaced by hyphen since default value of LimitInternalRecursion variable is 10.

这是使这些替换项适用于20个下划线的一种方法:

Here is one way you can make these replacements work for 20 underscores:

RewriteEngine On

# when there are more than one _ then "recursively" replace it by -
RewriteRule ^([^_]*)_+([^_]*_.+)$ $1-$2 [N,DPI]

# when there is only one / then replace it by _ and redirect
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [NE,L,R=301]

为什么它可以使用10次以上,因为我们使用的是 N 而不是第一条规则中的L 标志可提高整体效果。

Reason why it works for more than 10 replacements because we are using N instead of L flag in first rule that results in improving the overall performance.

这篇关于htaccess用连字符递归替换下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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