Htaccess,遍历文件直到存在?

Htaccess, go through files until exists?

我有这个 .htaccess 文件:

Options +FollowSymLinks
Options -Indexes

RewriteEngine On

RewriteEngine On

RewriteRule \.(png|jpg|gif|jpeg|bmp|ico|flv|mpeg|mp4|mp3|swf|exe|WAgame|wsc|eot|svg|ttf|woff|woff2|rar|wav)$ - []
RewriteRule ^ entryPoint3.php
RewriteRule ^ entryPoint2.php
RewriteRule ^ entryPoint.php

RewriteRule ^robots\.txt$ http://www.example.com [R,NE,L]
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST} [L,R=301]

<Files .htaccess>
Order Allow,Deny
Deny from All
</Files>

如果entryPoint3.php存在,加载它,否则加载entryPoint2.php,否则entryPoint.php。如何实现?

这样说:

Options +FollowSymLinks -Indexes
RewriteEngine On

RewriteRule \.(png|jpg|gif|jpeg|bmp|ico|flv|mpeg|mp4|mp3|swf|exe|WAgame|wsc|eot|svg|ttf|woff|woff2|rar|wav)$ - [L]

RewriteRule ^robots\.txt$ / [R,NC,L]

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# if entryPoint3 exists then use it
RewriteCond %{DOCUMENT_ROOT}/entryPoint3.php -f
RewriteRule ^ entryPoint3.php [L]

# if entryPoint2 exists then use it
RewriteCond %{DOCUMENT_ROOT}/entryPoint2.php -f
RewriteRule ^ entryPoint2.php [L]

# if entryPoint exists then use it
RewriteCond %{DOCUMENT_ROOT}/entryPoint.php -f
RewriteRule ^ entryPoint.php [L]

<Files .htaccess>
Order Allow,Deny
Deny from All
</Files>

I solved it like that: DirectoryIndex entryPoint3.php entryPoint2.php entryPoint.php what's the difference?

...but remember it will try to open entryPoint files in every directory not just in site root

您可以指定根目录相对 URL-路径作为 DirectoryIndex 指令的参数,它们不需要是 relative,因为您有这里。例如:

DirectoryIndex /entryPoint3.php /entryPoint2.php /entryPoint.php

这将只搜索文档根目录中的文件,而不管请求的是哪个目录。

而且,这与使用 mod_rewrite 的 完全不同(并且类似于您在问题中尝试的内容)。使用 DirectoryIndex,只有在您请求目录(包括文档根目录,即 https://example.com/)时,才会提供必要的文件。例如。 example.com/example.com/directory/ 将触发相关的 entryPoint 文件,但 example.com/something 不会。

但是,使用所述的 mod_rewrite 解决方案,相关 entryPoint 文件可用于请求的“任何”URL(少数 URL 扩展名除外规定的例外情况)。例如。 example.com/example.com/somethingexample.com/file.phpexample.com/directory/ 都会触发相关的 entryPoint 文件。

要使 mod_rewrite 解决方案以与 DirectoryIndex 相同的方式工作,您将需要一个额外的条件来明确检查请求是否映射到目录(包括尾部斜线)。例如:

# When requesting a directing... if entryPoint3 exists (in the root) then use it
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{DOCUMENT_ROOT}/entryPoint3.php -f
RewriteRule ^(.+/)?$ entryPoint3.php [L]
:

RewriteRule 模式 只是检查请求的 URL 是否以斜杠结尾(或者是文档根) - 与 [= 相同的行为13=]。 (如果您请求一个没有尾部斜杠的目录,那么 mod_dir 会附加一个 301 重定向。)

所以您选择的解决方案实际上取决于您的要求。但是,如果 DirectoryIndex 对你有用,那么我假设你只是在请求文件系统目录,所以 DirectoryIndex 是正确的选择。