【问题标题】:Confused about Htaccess对 Htaccess 感到困惑
【发布时间】:2015-06-05 22:33:56
【问题描述】:

我的 Htaccess 文件有点问题。

RewriteEngine On
RewriteBase /testwebsite/

RewriteRule ^home/?$ index.php

我想要完成的是:每当客户端访问 localhost/testwebsite/index.php 时,他必须被重定向到干净的 url (localhost/testwebsite/home)。每当访问者访问 localhost/testwebsite/home 时,他必须呆在那里,但仍然会显示 index.php 的内容。

目前每次访问 localhost/testwebsite/home 都会显示 index.php 的内容,但是每次访问 localhost/testwebsite/index.php 时,客户端仍然会看到“丑陋”的 url。

我在互联网上查找了所有信息,但 mod_rewriting 的工作原理并没有深入到我的脑海中。希望能得到帮助,谢谢!

【问题讨论】:

  • 我不确定它是如何实现的,但 Mod_rewrite 确实是掌握乒乓球的痛苦。我发现很多很多的试验和错误都有帮助。并学习 REGEX。

标签: php apache .htaccess mod-rewrite


【解决方案1】:

这是你需要做的。您可以在 .htaccess 中使用此代码。

RewriteEngine On
RewriteBase /testwebsite/
#redirect index.php to the pretty URL
RewriteCond %{THE_REQUEST} [A-Z]{3,}\ /testwebsite/index\.php
RewriteRule ^ home? [R=301,L]
#internally rewrite pretty URL to index file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^home/?$ index.php [L]

【讨论】:

  • 你能给我解释一下这究竟是如何工作的吗?非常感谢
  • 我在规则中几乎做到了。但只需在 Apache 的网站上查找变量。基本上我们检查请求,如果它是 index.php 然后我们重定向到 /home。如果 /home 被请求,我们会在内部重定向到 index.php。
  • 如果我在 PHP 本身中执行此操作会怎样?例如,询问 REQUEST_URI,然后验证用户是否访问 index.php,如果是,则使用 header 函数将他重定向到干净的 url?愚蠢的问题,因为它正在工作,但我也想知道这是否是一种“正确”的方式:P
  • 为什么需要混合 2 个?使用 Apache 处理重定向实际上更快。 .htaccess 在服务器端代码(PHP)之前读取和执行。因此,出于性能方面的考虑,我会离开它。另请检查此答案是否已接受。
  • 你刚刚说它对你有用?? since it's working but i'd also like to know if this is a "properly" way to do this
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 2012-07-22
  • 2013-05-13
  • 2020-04-16
  • 2023-03-08
  • 2019-08-04
相关资源
最近更新 更多