rewrite
我认为您的规则的最后一行有错字。
RewriteRule ^(.*)$ index.php/?u=$1 [L,QSA]
似乎应该更正为
RewriteRule ^(.*)$ index.php?u=$1 [L,QSA]
我在您的帖子中看到两个问题:
- 您想要获取斜线到下划线转换后的 URL 值。
- 当有人键入
/hi/hello/year
URL 时,应重定向到/hi_hello_year
.
URL 重写和重定向是两个独立的操作。
1. 斜线到下划线的转换
你已经有了$_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, '_' );
?>
2. 重定向到新的 URL
输入的人/hi/hello/year
应该会在他/她的浏览器中看到一个新的/hi_hello_year
URL。
这涉及到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.
?>
3.结合
但是,上述重定向是基于服务器有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();
?>