mod_rewrite:如何优先于文件夹优先文件 [英] mod_rewrite: how to prioritize files over folders
问题描述
我有这样的网址:
http://www.example.com/name1
http://www.example.com/name1/
http://www.example.com/name1/test1
我有一个看起来像这样的文件/文件夹结构
and I have a file/folder structure that looks like this
src
|
----name1.html
|
----name1
|
----test2.html
1)如果用户访问例如 http://www.example.com/name1
或 http://www.example.com/name1/
(带斜杠)我想投放html文件.
1) If a user visits e.g. http://www.example.com/name1
or http://www.example.com/name1/
(w/ trailing slash) I want to serve the html-file.
2)如果用户访问例如 http://www.example.com/name1/test1
我想提供 test1
文件夹内的html文件.
2) If a user visits e.g. http://www.example.com/name1/test1
I want to serve the html-file inside the folder test1
.
我可以在SO上找到的不同解决方案总是使用
The different solutions I could find on SO always use
RewriteCond %{REQUEST_FILENAME} !-d
以确保它不是目录-但我也想重写URL(如果它是现有目录),只要存在一个具有相同名称的html文件.
to make sure it isn't a directory - but I also want to rewrite the URL if it is an existing dir, as long as there is a html-file with the same name.
对您可以提供的任何输入感到满意.
Happy about any input you can provide.
欢呼
*编辑*
到目前为止,我看起来像这样
what I have so far looks something like this
RewriteEngine on
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [L]
推荐答案
您遇到的最大问题是 mod_dir
撤消了您尝试执行的所有操作.如果您有一个文件 test.php
和一个目录 test/
,其中包含 index.php
,则 mod_rewrite
重写请求,然后 mod_dir
将完全忽略该请求,并注入 test/index.php
作为url并重新创建.htaccess文件.要使其正常工作,您必须禁用 DirectoryIndex
.如果目录名称相同,为了防止Apache在URL后面自动添加斜杠,还必须关闭 DirectorySlash
.
The biggest problem you have is that mod_dir
undoes whatever you tried to do. If you have a file test.php
and a directory test/
with in it index.php
, mod_rewrite
will rewrite the request, and then mod_dir
will completely disregard that and inject test/index.php
as the url and do the .htaccess file all over again. To get this working, you have to disable DirectoryIndex
. To prevent Apache from automatically adding a slash after the url if there is a directory with the same name, DirectorySlash
must be turned off as well.
在那之后,这很简单.您可以匹配任何不带点的内容(只是为了避免不必要的文件检查),并在捕获组之外保留斜杠(如果存在的话).然后,您可以使用此捕获组(%1
)创建文件名以查看文件名是否存在.如果是这样,该请求将被重写.
After that, it is pretty straight-forward. You match anything without a dot (just so we don't do unnecessary file-checks) and leave a trailing slash, if one exists, outside the capture group. You then use this capture group (%1
) to create a filename to see if it exists. If it does, the request is rewritten.
DirectoryIndex disabled
DirectorySlash Off
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} ^([^.]*?)/?$
RewriteCond %1.html -f
RewriteRule ^([^.]*?)/?$ $1.html [L]
这篇关于mod_rewrite:如何优先于文件夹优先文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!