如果未找到文件/文件夹,则 mod 重写目录 [英] mod rewrite directory if file/folder not found

查看:28
本文介绍了如果未找到文件/文件夹,则 mod 重写目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的根目录中有一个名为folder1"的文件夹

I have a folder named "folder1" in my root directory

www.domain.com/www.domain.com/folder1

我需要将所有请求重定向到 www.domain.com,结果是 404 错误,到文件夹 1.像这样:

I need to redirect all the requests to www.domain.com that turn up to be a 404 error, to folder1. Like so:

www.domain.com/a_file.txt

如果 a_file.txt 不存在,请查看文件夹 1:

If a_file.txt doesn't exist, look in folder1:

www.domain.com/folder1/a_file.txt

我希望这对子目录也能正常工作,如下所示:

I want this to work the same for subdirectories, like so:

www.domain.com/a_folder(如果根目录中不存在则重定向)

www.domain.com/a_folder (redirect if it doesn't exist in the root)

www.domain.com/folder1/a_folder

我知道我应该使用 RewriteCond %{REQUEST_FILE} !-f 但我似乎无法弄清楚.

I know I should use RewriteCond %{REQUEST_FILE} !-f but I can't seem to figure it out.

推荐答案

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/folder1/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) folder1/$1 [L,R]

  • 第一个 rewrite-cond 确保您不会循环(以防该文件在 folder1 中也不存在
  • 第二个检查目标不是文件
  • 第三个 - 它也不是文件夹
  • 最后,重写 url.L 标志表示这是最后应用的规则(即使后面有规则),R 表示重定向.如果您希望将传递给原始的任何查询字符串参数发送到新的 url,您还可以添加 QSA 标志
    • The first rewrite-cond ensures you do not loop (in case the file does not exist inside folder1 either
    • The second one checks that target is not a file
    • The third - that it is not a folder either
    • And, finally, rewrite the url. L flag means this is the last rule applied (even if there are rules after it), R means redirect. You can also add QSA flag if you want any query-string parameters passed to the original be sent to the new url
    • 这篇关于如果未找到文件/文件夹,则 mod 重写目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆