简体   繁体   English

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

[英]In htaccess, I'd like to replace underscores with hyphens and then redirect the user the new url

I'd like to redirect any request that contains underscores to the same url, but with hyphens replacing the urls. 我想将包含下划线的任何请求重定向到相同的URL,但用连字符替换URL。 I've seen a lot of forums suggest I do something like this: 我见过很多论坛建议我这样做:

(Repeat an incremented version of this rewriteRule up to a gazillion) (重复此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]

My current solution in php is (which works fine): 我目前在php中的解决方案是(正常工作):

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

But, I'd rather not use php & instead keep it in my htaccess file without having to repeat that first rewriteRule over and over again in order to anticipate how many underscores each url might be. 但是,我宁愿不使用php&而是将其保存在我的htaccess文件中,而不必一遍又一遍地重复第一个rewriteRule以便预期每个URL可能有多少个下划线。 Thoughts? 有什么想法吗? Is there such a way to do this with out repeating the incremented rewriteRule? 有这样一种方法,而无需重复递增的rewriteRule吗?

----- edit ----- -----编辑-----

My current htaccess file is just the standard WordPress one, which is below: 我当前的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>

See the "Next" directive/rewrite flag, which causes the ruleset to be reevaluated starting with the first rule: http://httpd.apache.org/docs/current/rewrite/flags.html#flag_n 请参阅“下一个”指令/重写标志,该标志使规则集从第一个规则开始重新评估: http : //httpd.apache.org/docs/current/rewrite/flags.html#flag_n

Something like this might work: 这样的事情可能会起作用:

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

How about combining the 2. Have a single rewrite rule that rewrites to a PHP script that does the substitution and redirect. 如何合并2.如何使用一个重写规则来重写为执行替换和重定向的PHP脚本。 That way you avoid having multiple rewrite rules, can handle any number of underscores and only invoke the PHP redirection when it is needed. 这样,您可以避免使用多个重写规则,可以处理任意数量的下划线,并且仅在需要时才调用PHP重定向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM