nginx - NGINX - 为静态文件位置添加后缀
问题描述
我正在使用 nginx 来服务器静态图像文件。在我的目录中,所有图像都以扩展名 _.txt 存储(基本上重命名为.txt)。例如: background.png 将被存储为 background.png .txt
如何重定向 domain.com/images/background.png 的查找以查找 /static/images/background.png_.txt
到目前为止,这是我的 nginx 配置...
location /images/ {
alias /static/images/;
access_log off;
}
解决方案
这适用于我的服务器。它只是接受图像目录中某些内容的请求并检查它是否存在,然后检查它是否与.txt
扩展名一起存在,如果找不到,最后给出 404 错误。
location /images/ {
default_type "image/gif";
try_files $uri $uri.txt $uri =404;
}
只要确保你不复制location/images
块。如果它不存在,则添加它,但它应该已经存在,所以只需将try_files
行添加到它。
static
正如我在评论中所写,如果您的服务器在进入图像目录时尚未搜索,我会感到惊讶。但是,如果我共享的代码不起作用,您可以将修改后的图像文件的路径添加到块中,例如:
location /images/ {
root /home/username/path_to_site/domain.com/static/images;
default_type "image/gif";
try_files $uri $uri.txt $uri =404;
}
编辑
如果您检查响应标头,某些浏览器会显示以这种方式提供的图像content-type:text/plain
. 覆盖这一点的一种技巧是直接在图像位置块中指定类型:
location /images/ {
default_type "image/gif";
try_files $uri $uri.txt $uri =404;
types {
text/plain gif;
image/jpg jpeg jpg;
image/png png;
image/gif gif;
image/x-icon ico;
}
}
这些类型在 nginx 的其他地方定义,但是如果您不想在服务器的内部进行手术,这会更容易。重要的线是text/plain gif;
. 这将在图像目录中找到的任何文本文件定义为image/gif
.
最后的想法:这可能最好作为rewrite完成,但也许其他人知道该方法的细节。
推荐阅读
- mongodb - MongoExpress 显示“无法读取未定义的属性 'listDatabases'”错误
- c++ - C ++如何将Parent传递给需要Child的函数?
- c# - 使用带有 C# 的 AWS S3 程序集的问题
- c++ - 你如何反转strong_ordering?
- php - 将小数添加到脚本中的 PHP 输出
- swift - 首次调用信号时如何使用 Dispatch_Sempahore
- javascript - Telegraf 和云功能:如何阻止 Telegram Bot 接收无休止的旧更新
- javascript - 如何以角度在 ag grid masterdetail 的 detailCellRendererParams 内进行控制台
- shell - 如何使用 shell 脚本过滤字符串
- karate - 空手道加特林:未获取对功能文件的更改