0

所以我正在尝试在 PHP 中构建一个干净的 url 系统,以将这样的 URL 更改http://example.com/index.php?projects=05为:http://example.com/projects/05

到目前为止,我已经弄清楚了如何使用parse_url映射看起来像http://example.com/index.php/projects/05但我不知道如何从 URL 中删除“index.php”的 URL。有没有办法使用 .htaccessindex.php从 url 字符串中删除?

我知道这是一个简单的问题,但经过广泛的谷歌搜索,我找不到解决方案。

4

4 回答 4

1

您需要在 Apache 中使用 mod_rewrite 执行此操作。您需要将所有 URL 重定向到您的 index.php,然后,也许使用 parse_url,弄清楚如何处理它们。

例如:

# Turn on the rewrite engine
RewriteEngine On

# Only redirect if the request is not for index.php
RewriteCond %{REQUEST_URI} !^/index\.php

# and the request is not for an actual file
RewriteCond %{REQUEST_FILENAME} !-f

# or an actual folder
RewriteCond %{REQUEST_FILENAME} !-d

# finally, rewrite (not redirect) to index.php
RewriteRule .* index.php [L]
于 2012-05-25T06:02:45.243 回答
0

我正在使用以下 .htaccess 文件来删除 url 的 index.php 部分。

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /

# Protect hidden files from being viewed
<Files .*>
    Order Deny,Allow
    Deny From All
</Files>

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !favicon.ico$

RewriteRule .* index.php/$0 [PT]

否则我可以推荐 Kohana 框架作为参考(他们也有一个相当不错的 url 解析器和控制器系统)

于 2012-05-25T06:01:05.887 回答
0

在你的 .htaccess 中有这样的东西:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

(确保启用了重写模块)

于 2012-05-25T06:01:07.580 回答
0

将实际文件/文件夹与 URL 分离的概念称为路由。许多 PHP 框架都包含这种功能,主要使用mod_rewrite。有一篇关于PHP URL Routing的不错的博客文章,它实现了一个简单的独立路由器类。

它创建这样的映射:

mysite.com/projects/show/1 --> Projects::show(1)

所以请求的 URL 会导致调用show()类的函数,Projects参数为1.

您可以使用它来构建漂亮的 URL 到 PHP 代码的灵活映射。

于 2012-05-25T08:55:00.637 回答