如果存在于子目录中,则重写为文件

时间:2015-02-06 22:53:10

标签: apache .htaccess mod-rewrite

我有这样的文件结构:

root
 |- public
    |- file.jpeg
    |- file.txt
 |- .htaccess
 |- index.php

现在,我想将example.com/file.jpeg重写为example.com/public/file.jpeg,并将{。1}}目录中的file.txt和其他文件重写为相同,但如果该文件中不存在子目录然后重写为index.php

出于某种原因,这个.htaccess会将所有内容重写为index.php

public

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

您缺少RewriteCond来检查上一条规则中的现有文件/目录,因此将所有内容路由到index.php

您可以使用:

RewriteEngine On
RewriteBase /

# if direct access to /public needs be directed to index.php
RewriteCond %{THE_REQUEST} \s/+public [NC]
RewriteRule ^ index.php [L]

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

# if it is not /public/ then route to index.php
RewriteRule !^public/ index.php [L,NC]