mod_rewrite not changing URLs



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

输入后,myDomain.com/首先会带我进入myDomain.com/index.php?url=first,并在地址栏中显示myDomain.com/first。

但是,当单击类似href="index.php?url=first"的链接时,地址栏显示myDomain.com/index.php?url=当我希望它显示myDomain.com/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>

任何关于我的链接问题的建议或帮助都将不胜感激,提前感谢。

但是,当单击类似href="index.php?url=first"的链接时。地址栏显示myDomain.com/index.php?url=我想要的第一个显示myDomain.com/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>

看看这两行:

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

意思是:如果url指向真实的文件或文件夹,不要尝试以下规则

当您使用myDomain.com/index.php?url=first时,它指向一个真实的文件:index.php。那么,你的规则就不会被尝试了。

您必须在代码中始终使用类似myDomain.com/first的干净url。

最新更新