检查文件是否存在于子目录中,否则将所有内容redirect到主控制器

我想在Apache下的.htaccess文件中使用mod_rewrite进行如下操作:

  • 如果接收到任何文件或path的请求,例如foo.txtfoo/bar ,请检查public子目录中是否存在此文件,例如public/foo.txtpublic/foo/bar 。 它如果只是显示该文件。
  • 除此以外
    • redirect到主控制器index.php

我试图解决的是这样的:

 <IfModule mod_rewrite.c> RewriteEngine On # Don't rewrite requests for files in the 'public' directory RewriteRule ^(public)($|/) - [L] # For all other files first check if they exist in 'public' RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -f RewriteRule ^ public%{REQUEST_URI} [L] # Let 'index.php' handle everything else RewriteRule . index.php [L] </IfModule> 

不幸的是,存在一个主要的缺陷:它不能在子目录中工作,即当.htaccess和所有其他文件从//sub/ 。 理想情况下,它可以在任意子文件夹中工作,当然。

任何人都可以帮忙吗? 我怎样才能修复.htaccess来消除这个缺陷?

你似乎不想访问/公共文件夹以外的任何东西? 如果是这样,这对我来说似乎很容易,没有任何重写(我希望没有任何理由你真的使用mod_rewrite !)

  1. 把index.php放在公共文件夹中
  2. 将DocumentRoot设置为公用文件夹
  3. 使用ErrorDocument将未find的任何文件redirect到index.php

如果你有一个理由使用公共文件夹,那么你可以使用mod_rewriteredirect除index.php之外的任何东西,仍然使用ErrorDocumentredirect到index.php。

这个规则集适用于我。 我省略了开始/公开path的检查。

 RewriteEngine On RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -f RewriteRule ^/(.*) /public/$1 [L] RewriteRule . /index.html [L] 

如果/public不在您的文档根目录中,则可以将%{DOCUMENT_ROOT}replace为/ public目录中的磁盘path。 CONTEXT_DOCUMENT_ROOT可能包含到.htaccess文件的内容目录的文件path除非在/public/public具有与/public/public相同的文件,否则RewriteCond将不匹配。 我通过使用相当于/public作为我的文章来避免这个问题。 如果你不能把index.php放在/public ,你可以使用Alias来访问它。

你的方法涉及重写所有的匹配。 使用../public作为文档根目录的备用规则集是:

Alias /index.php /var/www/index.php RewriteCond%{REQUEST_FILENAME}!-f RewriteCond%{REQUEST_FILENAME}!-d RewriteRule。 /index.php [L]

您也可以使用自定义的404错误页面来处理丢失的文件。

尝试使用RewriteBase将其移动到子文件夹时:

 RewriteBase /subfolder/ # Rules