首页 > 解决方案 > 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;
    }       

标签: nginxnginx-location

解决方案


这适用于我的服务器。它只是接受图像目录中某些内容的请求并检查它是否存在,然后检查它是否与.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完成,但也许其他人知道该方法的细节。


推荐阅读