清理URL htaccess

时间:2012-01-14 08:53:13

标签: apache .htaccess mod-rewrite

如何将http://localhost/index.php?page=sample重写为http://localhost/page/sample

我的htaccess中唯一的代码是删除url上的index.php的规则。

RewriteCond %{THE_REQUEST} \ /(.+/)?index\.(html?|php)(\?.*)?\  [NC]
RewriteRule ^(.+/)?index\.(html?|php)$ ./$1 [R=301,L]
RewriteRule ^([^/]*)/$ ./index.php?page=$1  [QSA,L]

我正在寻找用参数重写零件。  谢谢!

2 个答案:

答案 0 :(得分:2)

规则是这样的:

RewriteRule ^page/([a-zA-Z0-9]+) index.php?page=$1 [L,NC]

答案 1 :(得分:2)

没有必要破解使用RewriteRules删除“index.php”。在你的vhost或per-directory conf(或者我不知道的.htaccess文件中),如果你提出了如下规则:

DirectoryIndex index.html index.php

然后它应该直接开箱即用。

所以我会这样做,好像你的规则不存在,因为它们没用(除非你告诉我原因)。

您希望用户键入浏览器:http://localhost/page/sample并在服务器端内部修改为:http://localhost/index.php?page=sample

这应该有效:

# if it's neither a file nor a directory:
RewriteCond %{REQUEST_FILENAME}!-f
RewriteCond %{REQUEST_FILENAME}!-d
RewriteRule /([^/]+)/([^/]+)$ /index.php?$1=$2 [QSA,L]

两个提示:

如果您不在托管环境中(=如果它是您自己的服务器并且您可以修改虚拟主机,而不仅仅是.htaccess文件),请尝试使用RewriteLog指令:它帮助您追踪此类问题:

# Trace:
# (!) file gets big quickly, remove in prod environments:
RewriteLog "/web/logs/mywebsite.rewrite.log"
RewriteLogLevel 9
RewriteEngine On

我最喜欢检查regexp的工具:

http://www.quanetic.com/Regex(别忘了选择ereg(POSIX)而不是preg(PCRE)!)