【问题标题】:mod_rewrite not changing URLsmod_rewrite 不改变 URL
【发布时间】:2012-08-24 23:57:05
【问题描述】:

所以我刚开始使用 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>

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

【问题讨论】:

标签: php apache .htaccess mod-rewrite


【解决方案1】:

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

【讨论】:

  • 是的,我可以通过使用 href="first" 让它按照我想要的方式工作,但这似乎不是正确的方法。也许我只是习惯于在 URL 中包含多个单词?
  • 这完全取决于“第一”的真正含义。首先什么?只要 URL 在您的应用程序上下文中有意义,就应该没问题。
  • 我使用“first”作为页面实际名称的占位符。但是first这个词或页面的名称是我在索引文件中的switch语句中使用的,以知道要包含哪个页面。
【解决方案2】:

看看这两行:

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

意思是:如果url指向一个真实的文件或文件夹,不要尝试遵循规则。

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

必须在代码中始终使用干净的 url,例如 myDomain.com/first

【讨论】:

  • 我尝试将这两行注释掉,但它仍然做同样的事情?
  • 你做错了。您不应删除这些行,而应在代码中使用 myDomain.com/first 而不是 myDomain.com/index.php?url=first
  • 啊...知道了,我确实是这样设置的,但我认为只有 href="first" 似乎不对,因为如果 mod_rewrite 曾经被关闭或没有工作,所有的链接都会中断。谢谢。
  • 如果mod_rewrite 不起作用,则意味着 Apache 已关闭,那么您的整个网站将无法运行,此时您不必真正关心 url ;)跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-29
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多