【问题标题】:Rewrite to file if that exists in subdirectory如果子目录中存在,则重写到文件
【发布时间】:2015-02-06 22:53:10
【问题描述】:

我有这样的文件结构:

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

现在,我想将 example.com/file.jpeg 重写为 example.com/public/file.jpeg 并且对于 file.txt 和 public 目录中的所有其他文件也是如此,但如果该文件在子目录中不存在,则重写为索引。 php

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

RewriteEngine On

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

RewriteRule ^(.*)$ index.php [L]

我的代码有什么问题?

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案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]
    

    【讨论】:

    • 但是根目录中的其他文件不会被重写,这是我想避免的。
    • 我想你不明白我的意思。我想将 /file.jpeg 重写为 /public/file.jpeg(如果存在),但对 index.php 的所有其他请求,甚至直接 /public/file.jpeg。这可能吗?
    • 是的,它是一个有效且现有的文件,但我不希望它可以作为 /public/a.jpeg 访问,只能作为 /a.jpeg 访问
    猜你喜欢
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多