2012-05-25 44 views
0

所以我想在PHP建立一个干净的URL系统改变像URL这样http://example.com/index.php?projects=05到:http://example.com/projects/05用PHP清理网址

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

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

回答

1

你需要在Apache中使用mod_rewrite来做到这一点。您需要将所有网址重定向到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] 
+0

我无法找到一种方式来使用.htaccess自动重定向 - 你能提供一个例子吗? – Thomas

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解析器和控制系统)

0

像这样的事情在你的.htaccess:

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

(请确保重写模块已启用)

0

您应该使用国防部重写的.htaccess中车削的index.php到/。

0

将实际文件/文件夹与URL解耦的概念称为路由。许多PHP框架都包含这种功能,主要使用mod_rewrite。在PHP URL Routing上有一篇很好的博文,它实现了一个简单的独立路由器类。

它创建这样的映射:

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

所以请求的URL导致类Projects的功能show()被调用,与1参数。

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