.htaccess - htaccess 递归地将下划线替换为连字符

标签 .htaccess redirect url-rewriting

我正在尝试将所有带下划线的网址重定向到同一网址,但下划线替换为连字符。

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

根据我的阅读,以下内容应该有效:

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

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

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

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

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

如何用尽可能少的规则将上面的下划线替换为连字符?

最佳答案

如果有超过 10 个下划线被连字符替换,这些实现之一将导致 500 内部错误,因为 LimitInternalRecursion 变量的默认值为 10。

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

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 标志,从而提高了整体性能。

关于.htaccess - htaccess 递归地将下划线替换为连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132730/

相关文章:

htaccess 更改后 WordPress 网站缺少图像

php - 重写 URL 的最有效方法

php - 加载特定的 PHP 版本

linux - Grep 在 .htaccess 中搜索重定向

.htaccess - 为什么这个 .htaccess 重定向不起作用?

php - CakePHP - Controller::flash() 不重定向

wordpress - wordpress .htaccess 中的文件夹索引

iis - Azure 网站规范主机名规则 - 循环重定向

regex - htaccess 从友好 URL 重定向到带参数的 URL

.htaccess 重定向到文件