如何使用 CloudFront 配置 Nginx 以从 CloudFront 的缓存中受益?

How to configure Nginx with CloudFront to benefit from CloudFront's caching?

我有一个使用 Wordpress 的网站。本网站托管在 Nginx 和 php-fpm 上。我添加了 CloudFront 以提高性能并减少源服务器负载。

但是,我可以在 Chrome 的开发人员工具控制台中看到所有资源在 x-cache header 中都有 Miss from CloudFront 值。

我不确定应该如何配置 Nginx 和 CloudFront 才能正常工作并从缓存中受益。

我相信 Nginx 应该设置适当的 headers(例如 Cache-Control: public 用于图像?)。我找不到任何可以涵盖所有情况并且不会弄乱 Wordpress 管理面板的示例(这个不应该被缓存,对吧?)。

一个快速修复可能是安装 WP Super Cache plugin;除其他外还支持 CDN。

在 Nginx 方面,您可以对静态内容执行类似这样的操作:

location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control "public";
}

您可以添加尽可能多的指令,而不仅仅是图像,例如:

location ~* \.(?:cur|gz|svg|mp4|ogg|ogv|webm|htc)$ {
     access_log off;
     add_header Cache-Control "max-age=2592000";
     #... more options
}

?: 前缀是一个 'non-capturing' 标记,这意味着我们不需要将模式捕获到 中,这应该有助于提高性能。

您可以找到有关 Nginx expires option here 的更多信息。