Mod Rewrite:用 - (连字符)替换所有_(下划线)

时间:2010-01-20 21:14:40

标签: apache mod-rewrite

我需要将每个网址中的所有_(下划线)替换为 - (连字符)

我目前这样做,但我正在寻找一种更简单的方法,所以每次网址变长时我都不必添加一行。

RewriteRule ^([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^.]+)-([^.]+)-([^.]+)-([^.]+)$ index.php?/$1_$2_$3_$4_$5_$6_$7_$8_$10 [L]
RewriteRule ^([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^.]+)-([^.]+)-([^.]+)$ index.php?/$1_$2_$3_$4_$5_$6_$7_$8_$9 [L]
RewriteRule ^([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^.]+)-([^.]+)$ index.php?/$1_$2_$3_$4_$5_$6_$7_$8 [L]
RewriteRule ^([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^.]+)$ index.php?/$1_$2_$3_$4_$5_$6_$7 [L]
RewriteRule ^([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^.]+)$ index.php?/$1_$2_$3_$4_$5_$6 [L]
RewriteRule ^([^_]+)-([^_]+)-([^_]+)-([^_]+)-([^.]+)$ index.php?/$1_$2_$3_$4_$5 [L]
RewriteRule ^([^_]+)-([^_]+)-([^_]+)-([^.]+)$ index.php?/$1_$2_$3_$4 [L]
RewriteRule ^([^_]+)-([^_]+)-([^.]+)$ index.php?/$1_$2_$3 [L]
RewriteRule ^([^_]+)-([^.]+)$ index.php?/$1_$2 [L]

感谢。

4 个答案:

答案 0 :(得分:3)

sedhyphen.sh

#!/bin/sh
sed -u 's/_/-/g'

httpd conf:

RewriteMap sed-hyphen prg:sedhyphen.sh
RewriteRule ^(.*)$ index.php?/${sed-hyphen:$1} [L]

确保sedhyphen.sh设置为可执行文件。

答案 1 :(得分:1)

我知道这是老问题,但这是我的解决方案。它不会浪费资源,它是SEO友好的,它不需要你使用bash,而是依赖于php

在重写引擎启动后将其放在.htaccess

RewriteCond %{REQUEST_URI} (.*)_(.*)
RewriteRule (.*)$ /tools/underscore_to_hyphen.php?rewrite_uri=$1 [NC,L]

这将发送您放置此代码的php脚本underscore_to_hyphen.php的所有文件:

<?php
$path = $_GET['unchanged_path'];
$input_uri = $_GET['rewrite_uri'];

$output_uri = str_replace("_", "-", $input_uri);

//For redirect uncoment:
header("HTTP/1.1 301 Moved Permanently");
header("Location: $path$output_uri");
exit();

//For rewrite uncoment:
//include_once "$_SERVER[DOCUMENT_ROOT]$path$output_uri";
?>

将把它发送到正确的地方。

因为这是.htaccess中没有重定向的重写规则,它将导致用户/蜘蛛的单个重定向或重写。

请注意,这只是部分测试,我反过来使用它,将-更改为_

答案 2 :(得分:0)

mod_rewrite不是这种工作的好工具。你为什么不用PHP代替?

$_SERVER['QUERY_STRING'] = str_replace('_', '-', $_SERVER['QUERY_STRING']);

编辑您可以试试这些规则集:

# using the path
RewriteRule ^([^-]+)-([^-]+-.+) /$1_$2 [N]
RewriteRule ^([^-]+)-(.+) index.php?/$1_$2 [L]

# using the query
RewriteRule ^([^-]+)-(.+) index.php?/$1_$2
RewriteCond %{QUERY_STRING} ^([^-]+)-(.+)
RewriteRule ^index\.php$ ?$1_$2 [N]
RewriteRule ^index\.php$ - [L]

但要注意 N 标志,因为您可以轻松获得无限递归。

答案 3 :(得分:0)

也许这就是:

RewriteCond %{REQUEST_URI} ^(.*)_(.*)/$
RewriteRule (.*)_(.*)/ http://your-site.com$1-$2/ [R=301]
相关问题