php - 在 htaccess 中,我想用连字符替换下划线,然后将用户重定向到新的 url

标签 php .htaccess mod-rewrite redirect

我想将任何包含下划线的请求重定向到相同的 url,但用连字符替换 url。我看到很多论坛都建议我这样做:

(重复此 rewriteRule 的递增版本,直到无数次)

rewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ http://example.com/$1-$2-$3-$4 [R=301,L]
rewriteRule ^([^_]*)_([^_]*)_(.*)$ http://example.com/$1-$2-$3 [R=301,L]
rewriteRule ^([^_]*)_(.*)$ http://example.com/$1-$2 [R=301,L]

我目前在 php 中的解决方案是(工作正常):

if(preg_match('/[_]+/', $_SERVER['REQUEST_URI'])){
    $redirectUrl = preg_replace('/[_]+/','-', $_SERVER['REQUEST_URI']);
    header('Location: '. $redirectUrl , TRUE, 301);
    return;
}

但是,我宁愿不使用 php,而是将它保存在我的 htaccess 文件中,而不必一遍又一遍地重复第一个 rewriteRule 以预测每个 url 可能有多少下划线。想法?有没有一种方法可以在不重复递增的 rewriteRule 的情况下做到这一点?

-----编辑-----

我当前的 htaccess 文件只是标准的 WordPress 文件,如下所示:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

最佳答案

请参阅“Next”指令/重写标志,它会导致从第一条规则开始重新评估规则集:http://httpd.apache.org/docs/current/rewrite/flags.html#flag_n

这样的事情可能会起作用:

RewriteRule (.*)_(.*) $1-$2 [N] 

关于php - 在 htaccess 中,我想用连字符替换下划线,然后将用户重定向到新的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7650542/

相关文章:

php - .htaccess 用/为每个 PHP 文件替换 .php

php - 数据没有进入mysql

javascript - 使用来自 Symfony Controller 的加载微调器将 Ajax 请求引入 Bootstrap 模式

.htaccess - htaccess 将文件请求从特定文件夹重定向到另一个主机名

php - 在 Wordpress(或 .htaccess)中创建 URL 别名

apache - .htaccess 从 http 重定向到 https

php - 用户名和通过mysql数据库登录

php - 在将其插入数据库之前如何检查数据库中已存在的表单值?

html - 在静态 html 着陆页中路由

.htaccess - 适用于 Internet Explorer 11 的 SSLCipherSuite