【发布时间】:2014-05-05 10:01:06
【问题描述】:
我试图在我的 localhost 上实现干净的 URL(所以当我写 localhost/contact 时,它会将我重定向到 localhost/contact.php),但它不起作用。我是根据我在 YouTube 上找到的较早的教程进行的,但我可能对某些部分不太了解。非常感谢您的每一个回答。这是我的代码:
.htaccess // 我确定我允许 mod_rewrite。
<IfModule mod_rewrite.so>
RewriteEngine On
RewriteBase /www/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1
</IfModule>
index.php 中的脚本
include_once('classes/simpleUrl.php');
$url = new simpleUrl('localhost');
$test = $url->segment(1);
if (!$url->segment(1)) {
$page = 'home';
}
else {
$page = $url->segment(1);
}
switch ($page) {
case 'home' :
echo 'Home page';
break;
case 'contact':
echo 'Contacts page';
break;
default:
echo '404';
break;
}
类/simpleUrl.php
class simpleUrl {
var $site_path;
function __toString() {
return $this->site_path;
}
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
return $string;
}
}
function __construct($site_path) {
$this->site_path = $this->removeSlash($site_path);
}
function segment($segment) {
$url = str_replace($this->site_path, '', $_SERVER['REQUEST_URI']);
$url = explode('/', $url);
if(isset($url[$segment])) {return $url[$segment];} else {return false;}
return $url;
}
【问题讨论】:
-
详细解释“不工作”的含义会很有帮助。您是否可以显示错误/警告?
-
另外,从我在您的示例代码中看到的,您似乎正在打印“主页”、“联系人页面”,而不是实际重定向到 contact.php。这是您正在运行的实际代码吗?
-
是的,这个回显是临时解决方案,看看它是否有效,稍后我将使用包含功能。当我键入 localhost/url 时,它给了我基本错误“/url”未在此服务器上找到。
标签: php apache .htaccess mod-rewrite clean-urls