1

所以我刚开始使用 Apache 的 mod_rewrite 模块,我遇到了一个我似乎无法弄清楚的问题。我想要的是让地址栏在用户手动输入 URL 或链接到页面时显示干净的 URL。现在,当我输入它们时,我得到了干净的 URL,但是当页面链接到时,查询字符串仍然显示在地址栏中。例如:

输入 myDomain.com/first 会将我带到 myDomain.com/index.php?url=first 的页面,并在地址栏中显示 myDomain.com/first。

但是,当单击 href="index.php?url=first" 之类的链接时。当我希望它显示 myDomain.com/first 时,地址栏会显示 myDomain.com/index.php?url=first。

这是我的 .htaccess 文件,它与我的索引文件位于同一文件夹中:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_\-]+)/?$ index.php?url=$1 [NC,L]
</IfModule>

这是我的索引文件:

<?php
define('ROOT_DIR', dirname(__FILE__) . '/'); // Define the root directory for use in includes 
require_once (ROOT_DIR . 'library/bootstrap.php');

$url = strtolower($_GET['url']);

include(ROOT_DIR . 'views/headerView.php');

switch($url)
{
    case "first": include(ROOT_DIR . 'views/firstPageView.php');
        break;
    case "second": include(ROOT_DIR . 'views/secondPageView.php');
        break;
    default: include(ROOT_DIR . 'views/homeView.php');
} 

include 'views/footerView.php';
?>

这是 homeView.php:

<p>This is the home page.</p>
<p>To the first page. <a href="index.php?url=first">First Page</a></p>
<p>To the second page. <a href="index.php?url=second">Second Page</a></p>

对于我的链接问题的任何建议或帮助将不胜感激,在此先感谢您。

4

2 回答 2

1

但是,当单击 href="index.php?url=first" 之类的链接时。当我希望它显示 myDomain.com/first 时,地址栏会显示 myDomain.com/index.php?url=first。

您必须链接到“干净”的 URL。请记住,您不是在此处重定向。你在重写!这意味着你必须改变这个:

<p>This is the home page.</p>
<p>To the first page. <a href="index.php?url=first">First Page</a></p>
<p>To the second page. <a href="index.php?url=second">Second Page</a></p>

对于这样的事情:

<p>This is the home page.</p>
<p>To the first page. <a href="/url/first">First Page</a></p>
<p>To the second page. <a href="/url/second">Second Page</a></p>
于 2012-08-30T09:29:45.897 回答
0

看这两行:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

这意味着:如果 url 指向真实的文件或文件夹,请不要尝试遵循规则。

使用时myDomain.com/index.php?url=first,它指向一个真实的文件:index.php. 然后,您的规则将不会被尝试。

必须myDomain.com/first始终像在代码中一样使用干净的 url 。

于 2012-08-30T09:30:55.803 回答