问题
I have URLs like this:
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) 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) If a user visits e.g. http://www.example.com/name1/test1
I want to serve the html-file inside the folder test1
.
The different solutions I could find on SO always use
RewriteCond %{REQUEST_FILENAME} !-d
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.
cheers
* edit *
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]
回答1:
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.
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]
来源:https://stackoverflow.com/questions/28171874/mod-rewrite-how-to-prioritize-files-over-folders