如何使用 NGINX 缓存 NextJS 10.0 图像

Posted

技术标签:

【中文标题】如何使用 NGINX 缓存 NextJS 10.0 图像【英文标题】:How to cache NextJS 10.0 images using NGINX 【发布时间】:2021-03-06 09:21:05 【问题描述】:

我们想使用 nginx 启动 NextJS 10 应用,因此我们使用类似于以下配置:

location /_next/static/ 
    alias /home/ec2-user/my-app/.next/static/;
    expires 1y;
    access_log on;

效果很好,它可以将我们的静态数据缓存一年,但是当我们使用 NextJS images 时,我无法在动态调整大小的图像上添加 expires 标记。

如果我这样做:

location /_next/image/ 
    alias /home/ec2-user/my-app/.next/image;
    expires 1y;
    access_log on;

它只是在图像上返回 404。

这是我的服务器部分 NGINX 配置:

server 
    listen 80;
    server_name *.my-website.com;
    # root        /usr/share/nginx/html;
    # root /home/ec2-user/my-app;
    charset     utf-8;

    client_max_body_size    20M;
    client_body_buffer_size 20M;

    proxy_connect_timeout    600;
    proxy_send_timeout       600;
    proxy_read_timeout       600;
    send_timeout             600;

    underscores_in_headers on;

    add_header X-Frame-Options SAMEORIGIN always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "same-origin" always;

    location = /robots.txt 
        proxy_pass https://api.my-website.com/robots.txt;
    

    location /_next/static/ 
        alias /home/ec2-user/my-app/.next/static/;
        expires 1y;
        access_log on;
    

    location / 
        # reverse proxy for merchant next server
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass_request_headers      on;
        proxy_cache_bypass $http_upgrade;
        proxy_buffering off;
    

【问题讨论】:

显示你的 NextJS 相关的 nginx 配置部分,因为它现在正在寻找。 问题已编辑@IvanShatsky 【参考方案1】:

这是一个示例,您可以如何依赖上游 Content-Type 标头来设置 ExpiresCache-Control 标头:

map $upstream_http_content_type $expire 
    ~^image/    1y; # 'image/*' content type
    default     off;

server 
    ...
    location / 
        # reverse proxy for merchant next server
        proxy_pass http://localhost:3000;
        ...
        expires $expire;
    

您可以为任何其他内容类型的代理响应调整缓存控制标头的相同方式。 $upstream_http_<name> nginx 变量描述为here。

更新

要仅通过特定 URI 添加缓存控制标头,您可以使用两个链接的 map 块:

map $uri $expire_by_uri 
    ~^/_next/image/    1y;
    default            off;

map $upstream_http_content_type $expire 
    ~^image/           $expire_by_uri;
    default            off;

如果您除了来自/_next/image/... URI 的图像之外别无其他,您可以使用

map $uri $expire 
    ~^/_next/image/    1y;
    default            off;

【讨论】:

谢谢@IvanShatsky 有效,但这并不是我真正需要的,因为我只想缓存 /_next/image/ 图像。无论如何我都会接受。谢谢你:)

以上是关于如何使用 NGINX 缓存 NextJS 10.0 图像的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 NGINX 部署 NextJS?

nextjs ssr数据缓存

作为道具传递与提取缓存 Apollo 客户端 Nextjs

在 NextJS、nginx 和 Material-ui(s-s-r) 中使用 CSP

Nextjs getInitialProps 不适用于 NGINX

如何在NGINX中路由静态文件和不同的应用程序?