【问题标题】:htaccess - Rewrite files that have a directory with the same namehtaccess - 重写具有同名目录的文件
【发布时间】:2013-11-18 02:41:51
【问题描述】:

我有一个网站,其中包含多个同名的 PHP 文件和目录,如下所示:

/projects.php
/projects
/projects/something.php

我已经设法使用以下规则将http://example.com/projects 重写为http://example.com/projects.php(使用答案here):

RewriteEngine On

# Disable automatic directory detection
DirectorySlash Off

# Hide extension
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

但是,当我将目录斜线明确输入到 URL 时,它会访问该文件夹。 现在:

http://example.com/projects   -->  http://example.com/projects.php  [file]
http://example.com/projects/  -->  http://example.com/projects/     [folder]

我知道它为什么这样做(projects/.php 不是文件)。我修复它的尝试包括检查它是否是一个文件夹,然后用空替换斜杠并访问它。

新的.htaccess:

RewriteEngine On

# Disable automatic directory detection
DirectorySlash Off

# Hide extension
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

# Folder fix
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*)/$ $1.php

这按预期工作,但是它在客户端完全搞砸了,因为客户端的 URL 中仍然有一个文件夹,所以当它尝试获取相对路径时,它会惨遭失败。

现在我考虑使用 [R=301] 标志进行重定向,但据我所知,%{REQUEST_FILENAME} 是相对于服务器的,因此重定向到该标志行不通。

如果有人能指出我正确的方向,将不胜感激!

【问题讨论】:

  • 我的文件夹名称也是“项目”,这太疯狂了 xd

标签: php regex apache .htaccess mod-rewrite


【解决方案1】:

尝试将此行放在顶部:

Options -MultiViews

Read More About it

您的 .php 隐藏规则应为:

RewriteEngine On

# Disable automatic directory detection
DirectorySlash Off

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

【讨论】:

  • 不幸的是,这并不能解决我的问题。不过谢谢,学到了新东西!
  • 这也不起作用。现在example.com/projects 指向文件夹。
  • 所以example.com/projects 没有加载example.com/projects.php 并打开文件夹example.com/projects/
  • 确切地说,可能是由于RewriteCond %{REQUEST_FILENAME} !-d。有什么想法吗?
  • 我刚刚通过创建一个名为 projects.php 的文件和一个文件夹项目对此进行了测试,它对我有用。
猜你喜欢
  • 1970-01-01
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多