从example.com/test.php/foo/bar中删除.php

时间:2013-04-03 16:40:38

标签: php .htaccess mod-rewrite url-rewriting rewrite

我正在寻找一种方法来简单地从网址中删除“.php”而忽略.php之后的所有内容

因此example.com/test.php/foo/bar将成为example.com/test/foo/bar

然后在PHP模板中我可以搜索并使用foo或bar。我发现删除.php的所有内容都会干扰最后的变量。

更新:通过从文件名中删除.php然后使用ForceType,我发现了一些成功。虽然如果我能保留.php扩展名仍然很好,所以我的代码编辑器知道如何突出显示语法:)

<FilesMatch "^test$">
    ForceType application/x-httpd-php5
</FilesMatch>

更新2 这是我尝试使用的RewriteRule取得了一些成功,但是当我添加一个尾部斜杠和一些内容后,会导致500内部服务器错误

RewriteEngine On
RewriteBase /
# remove .php; use THE_REQUEST to prevent infinite loops
    RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
    RewriteRule (.*)\.php$ $1 [R=301]
# remove index
    RewriteRule (.*)/index$ $1/ [R=301]
# remove slash if not directory
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} /$
    RewriteRule (.*)/ $1 [R=301]
# add .php to access file, but don't redirect
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteCond %{REQUEST_URI} !/$
    RewriteRule (.*) $1\.php [L]

2 个答案:

答案 0 :(得分:2)

你的最后一块几乎就在那里。但是,您需要更大的RewriteCond种类才能使其与可选的PATH_INFO一起使用。

即你需要首先匹配REQUEST_FILENAME / _URI中的单词字符,然后然后测试是否存在类似命名的.php脚本:

RewriteCond %{REQUEST_URI}           ^/(w+)/
RewriteCond %{DOCUMENT_ROOT}/%1.php  -f
RewriteRule ^(\w+)/(.+)$ $1.php/$2   [L]

最后一个RewriteRule取决于现有的尾随变量。为没有PATH_INFO的普通http://example.com/test请求添加一个通用规则块。请注意,此特定集仅适用于webroot中的xyz.php脚本。

答案 1 :(得分:0)

请尝试重新检查:

RewriteCond %{REQUEST_URI} ^/([a-z0-9-_]+)/([a-z0-9-_]+)/([a-z0-9-_]+)/?$
RewriteRule ^(.*) ^/%1.php/%2/%3
相关问题