Nginx 静态图像不缓存

Nginx 静态图像不缓存

我有一个在 apache2 上运行的 Magento 网站,前端是 PWA 并在 Nginx 上运行,我正在使用 Cloudflare。现在想缓存图像,但它总是显示 BYPASS。Apache 配置:

<VirtualHost 127.0.0.1:8081>
        SSLEngine On
        SSLCertificateFile /etc/nginx/ssl/cloudflare.crt
        SSLCertificateKeyFile /etc/nginx/ssl/cloudflare.key

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        ServerName stg.mydomain.com
        ServerAlias stg.mydomain.com
        Alias /backend "/var/www/backend/public_html"
        DocumentRoot "/var/www/backend/public_html"
        <Directory "/var/www/backend/public_html">
                DirectoryIndex index.php index.html index.htm
                Options Indexes FollowSymLinks
                AllowOverride All
                Require all granted
        </Directory>

</VirtualHost>

Nginx 配置:

server {
    listen 80;
    listen 443 ssl http2;
    ssl_certificate /etc/nginx/ssl/cloudflare.crt;
    ssl_certificate_key /etc/nginx/ssl/cloudflare.key;

    server_name stg.mydomain.com;   
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_read_timeout 720s;
    proxy_connect_timeout 720s;
    proxy_send_timeout 720s;
        proxy_redirect        off; 
    location / {
     proxy_pass http://127.0.0.1:9000;
        }
    location /backend {
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass https://127.0.0.1:8081;  
    }   
}

我添加了以下代码来缓存浏览器中的图像

server {
    listen 80;
    listen 443 ssl http2;
    ssl_certificate /etc/nginx/ssl/cloudflare.crt;
    ssl_certificate_key /etc/nginx/ssl/cloudflare.key;

    server_name stg.mydomain.com;   
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_read_timeout 720s;
    proxy_connect_timeout 720s;
    proxy_send_timeout 720s;
        proxy_redirect        off; 
    location / {
     proxy_pass http://127.0.0.1:9000;
        }
        location ~* .(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc|webp)$ {
      expires 1d;
        add_header Cache-Control "public";
    }
    location /backend { 
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass https://127.0.0.1:8081;  
    }   
}

答案1

首先 - 它不缓存,因为你没有告诉 nginx 缓存任何内容:proxy_cache设置为离开默认情况下。您应该定义一个代理区域并相应地使用它。

第二 - 通过 Apache 处理静态对象毫无意义。你应该做的是将所有静态对象直接指向文件系统,方法是添加类似

location ~*.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc|webp)$ {
      expires @30d;
}

相关内容