如果输入类似http://someone.com/hi/hello/yeah
的内容,如何重写网址,我希望结果为http://someone.com/?u=hi_hello_yeah
这是我到目前为止所写的,它只替换了没有斜杠的网址“/”
RewriteEngine on
RewriteCond $1 !^(index\.php|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/?u=$1 [L,QSA]
而且,我希望如果用户输入http://someone.com/hi/hello/yeah
,它会重定向到http://someone.com/hi_hello_yeah
答案 0 :(得分:1)
我认为rewrite
规则的最后一行有一个拼写错误。
RewriteRule ^(.*)$ index.php/?u=$1 [L,QSA]
似乎应该更正
RewriteRule ^(.*)$ index.php?u=$1 [L,QSA]
我在帖子中看到两个问题:
/hi/hello/year
中输入时,网址应 重定向 到/hi_hello_year
。网址重写和重定向是两项独立的操作。
您已拥有$_GET['u']
变量,其中包含/hi/hello/year
只需str_replace
它就会为您提供转换后的URI字符串。
<?
// this is the landing index.php page specified in the last rewrite rule.
// should be "/hi/hello/year" for "/hi/hello/year" URL request.
$rewritten_uri = isset($_GET['u']) ? $_GET['u'] : '';
// converting slashes to underscores.
$converted_uri = str_replace( '/', '_', $rewritten_uri );
// the string begins and/or ends with a slash, so remove it.
$ready_to_use_uri = trim( $converted_uri, '_' );
?>
输入/hi/hello/year
的人应该在他/她的浏览器中看到一个新的/hi_hello_year
网址。
这涉及header( "Location: ..." )
;
<?
$new_url = '/' . $ready_to_use_uri; // which came from the above code
header( 'Location: ' . $new_url );
exit(); // unless you have some more work to do.
?>
但是,上面的重定向是基于服务器具有hi_hello_year
文档的假设,否则可能会导致无休止的rewrite
- redirect
循环。让我们结合并添加一个安全措施。
<?
// this is the landing index.php page specified in the last rewrite rule.
// should be "/hi/hello/year" for "/hi/hello/year" URL request.
$rewritten_uri = isset($_GET['u']) ? $_GET['u'] : '';
// converting slashes to underscores.
$converted_uri = str_replace( '/', '_', $rewritten_uri );
// the string begins and/or ends with a slash, so remove it.
$ready_to_use_uri = trim( $converted_uri, '_' );
// redirect only when such file exists
if ( file_exist( $ready_to_use_uri ) )
{
header( 'Location: /' . $ready_to_use_uri );
exit(); // unless you have some more work to do.
}
header("HTTP/1.0 404 Not Found");
echo "The document '" . $ready_to_use_uri . "' is not found on this server";
exit();
?>
答案 1 :(得分:0)
这很棘手,因为它需要递归应用重写规则。
通过httpd.conf
启用mod_rewrite和.htaccess,然后将此代码放在.htaccess
目录下的DOCUMENT_ROOT
中:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
# this recursive rule will be applied as many times as the /s in the URI
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/(.+)$ /$1_$2 [L]
# this rule will be applied once all /s have been replaced by _
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /?u=$1 [L,QSA]