apache - .htaccess 重写/foo/bar/to/foo/bar.php

标签 apache .htaccess mod-rewrite

我希望在 .htaccess 文件中设置规则,以便可以通过仅用斜杠替换扩展名来访问具有 .php 扩展名的所有文件(/foo/bar/ 会默默地加载/foo/bar.php)。之前我发现this ,这正是我正在寻找的,只不过它仅将 /foo/bar.php 更改为 /foo/bar (注意没有结束斜杠)。

对于 htaccess,我几乎是个新手,对上一个链接中的代码进行了大约 30 分钟的调整,但没有产生大量 500 内部服务器错误。我确信这是一个非常简单的修复,但 Google 和反复试验都还没有给我带来任何结果。

任何人都可以看一下上述帖子中的代码(复制在下面)并更改它,以便 /foo/bar/ 将重写为 /foo/bar.php?

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

非常感谢!

最佳答案

根据下面的评论,目的是让用户可见的 URL(如/foo/bar/)实际运行 php 脚本(如/foo/bar.php)。此外,您可能希望尝试直接加载/foo/bar.php 的用户被重定向到/foo/bar/以保持一致性。

#Redirect users loading /foo/bar.php to /foo/bar/
RewriteRule ^(.*)\.php$ $1/ [R]

#Rewrite /foo/bar/ (what the user sees) silently to /foo/bar.php
RewriteRule ^(.*)/$ $1.php [L]

第一条规则末尾的[R]指定重定向而不是重写,以便用户加载/foo/bar/。第二条规则末尾的 $1 与括号(终止斜杠之前的所有内容)匹配,然后在末尾添加 .php。 [L] 表示停止评估 RewriteRules

正如我原来的回复中一样,替换字符串的前导斜杠的使用取决于上下文。通过这些规则,您将能够看到第一条规则的效果,因为它是重定向。如果重定向尝试转到 mydomain.comfoo/bar/ 而不是 mydomain.com/foo/bar/,则在 $1< 之前添加前导斜杠 在每个规则中。

另一个注意事项 - 您的 php 脚本是否需要任何查询字符串?如果确实如此,可能需要进行额外的调整。

Apache mod_rewrite reference有更多详细信息。

关于apache - .htaccess 重写/foo/bar/to/foo/bar.php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14432305/

相关文章:

java - Tomcat Server.xml 中的动态通配符设置(非 www)

android - Apache Commons 网络 API 无法在 Android ICS(4.0) 上运行

php - 是否可以使用 .htaccess 制作自定义页面索引?如果是这样怎么办?

.htaccess - 在 htaccess 中重定向许多旧的 asp 页面

php - 子文件夹中的 .htaccess 不起作用

php - htaccess 重写不带 .php 扩展名的 URL 到文件

Apache 重写规则将所有请求重定向到包含另一个 .htaccess 和重写规则的子目录

php - UTF-8贯穿始终

apache - Activemq、Redis 和 Apache camel 是正确的组合吗?

apache - 不要在子域上应用重写引擎......?