0

http://someone.com/hi/hello/yeah如果我输入类似的内容并且我希望结果是,如何重写 URLhttp://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

4

2 回答 2

1

rewrite我认为您的规则的最后一行有错字。

RewriteRule ^(.*)$ index.php/?u=$1 [L,QSA]

似乎应该更正为

RewriteRule ^(.*)$ index.php?u=$1 [L,QSA]

我在您的帖子中看到两个问题:

  1. 您想要获取斜线到下划线转换后的 URL 值。
  2. 当有人键入/hi/hello/yearURL 时,应重定向/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_yearURL。
这涉及到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();
?>
于 2013-08-05T06:01:58.767 回答
0

这很棘手,因为它需要递归应用重写规则。

通过启用 mod_rewrite 和 .htaccess httpd.conf,然后将此代码放在您.htaccessDOCUMENT_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]
于 2013-08-05T05:21:26.673 回答