.htaccess在目录中重写 - 隐藏PHP扩展并强制尾随斜杠

时间:2011-04-03 05:30:25

标签: apache .htaccess mod-rewrite

我正在尝试隐藏文件中的.php扩展名,并在生成的网址上强制使用斜杠。

示例:对/about.php的请求将成为/ about /,对/ about的请求将转至/ about /.

当我在hostdomain的根目录时,以下重写代码完美运行:

RewriteEngine On
RewriteRule ^(.*)/$ /$1.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://edit.mydomain.org/$1/ [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)\.php\ HTTP/ [NC]
RewriteRule .+ http://edit.mydomain.org/%1  [R=301,QSA]

但是,我需要将我的文件移动到此主机名的目录中。将目录名添加到规则中并在目录中使用.htaccess根本不起作用,并且似乎导致无限重定向。

我浏览了StackOverflow和其他网站并尝试了大量示例,最终出现了许多不同的错误:

  • 一切都是无休止的重定向。
  • 目录主页以外的所有内容都是500错误。
  • about.php重定向到/ about但是没有重定向到/ about /和/ about /显示500错误。
  • 一切正常,但主页(目录)index.php在没有文件名的情况下访问时会进入无限重定向。
  • 重定向到edit.mydomain.org/home/username/public_html/mydomain.org/edit/pagename.php的内容显然不存在。

感谢您的帮助!我真的需要将这些文件保存在一个目录中,尽管.htaccess可以在需要时进入主机名root。

这个目录是edit.mydomain.org/dave /

2 个答案:

答案 0 :(得分:3)

将其另存为.htaccess并将其放入'dave'目录

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\..+$
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.*)$ http://edit.mydomain.org/dave/$1/ [R=301,L]

RewriteRule ^(.*)/$ $1.php [L]

答案 1 :(得分:1)

这对我有用

RewriteBase /
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html