首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.htaccess规则-检查请求是针对文件夹还是文件?

.htaccess规则-检查请求是针对文件夹还是文件?
EN

Stack Overflow用户
提问于 2013-06-20 21:01:43
回答 2查看 2.9K关注 0票数 1

我需要检查请求的URL,并根据请求是针对文件还是目录提供不同的选项。

我的URL看起来应该是:

  • http://www.example.com/Services/Service-1 (目录,服务/pages/Services/Service1/index.php)
  • http://www.example.com/Services/Service-1/Feature-1/Sub-Feature (一个实际的文件,服务/pages/Services/Service-1/Feature-1/Sub-Feature.php)

由于我对.htaccess缺乏了解(这需要RewriteCondition吗?),目前我不得不列举目录结构中的每个文件夹,如下所示:

代码语言:javascript
复制
RewriteRule ^Services/Service-1/(.*)$ /pages/Services/Service-1/$1.php
RewriteRule ^Services/Service-1 /pages/Services/Service-1/index.php

RewriteRule ^Services/Service-2/(.*)$ /pages/Services/Service-2/$1.php
RewriteRule ^Services/Service-2 /pages/Services/Service-2/index.php

RewriteRule ^Services/(.*)$ /pages/Services/$1.php
RewriteRule ^Services /pages/Services/index.php

RewriteRule ^Testimonials/(.*)$ /pages/Testimonials/$1.php
RewriteRule ^Testimonials /pages/Testimonials/index.php

不用说,这是一个真正的痛苦-任何时候我添加文件夹的内容,我必须混乱的.htaccess。

我知道一定有更好的方法,但我的谷歌和堆叠溢出搜索没有发现任何工作,当我尝试它。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-06-20 21:28:23

您猜对了,可以使用rewriteCond来验证所请求的uri是文件还是目录:

代码语言:javascript
复制
# f for a file, d for a directory
RewriteCond %{REQUEST_FILENAME} -f 

你的.htaccess应该是:

代码语言:javascript
复制
Options -MultiViews
RewriteEngine ON    

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.+) /$1/index.php [QSA,L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.+) /$1.php [QSA,L]

编辑:如果文件驻留在页面子目录中,则必须使用以下代码:

代码语言:javascript
复制
Options -MultiViews
RewriteEngine ON    

RewriteCond %{DOCUMENT_ROOT}/pages/$1 -d
RewriteRule (.+) /pages/$1/index.php [QSA,L]

RewriteCond %{DOCUMENT_ROOT}/pages/$1.php -f
RewriteRule (.+) /pages/$1.php [QSA,L]
票数 3
EN

Stack Overflow用户

发布于 2013-06-20 21:36:28

到目前为止,如果启用了mod协商,最简单的(通常是):

代码语言:javascript
复制
Options MultiViews
MultiviewsMatch Any
DirectoryIndex index.php

但是不会强制使用.php,如果您有somefile.html和somefile.php,通常会选择.html文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17223695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档