【问题标题】:NGINX+Wordpress Caching paradoxNGINX+Wordpress 缓存悖论
【发布时间】:2019-02-11 23:11:27
【问题描述】:

我正在运行 Wordpress + NGINX + PHM-FPM。我已经对我的 NGINX 配置进行了这些更改,这些更改来自我遇到的最佳实践文章:

#Don't cache if there is a cookie called PHPSESSID
if ($http_cookie ~* "PHPSESSID"){
    set $no_cache 1;
}

#Don't cache if there is a cookie called wordpress_logged_in_[hash]
if ($http_cookie ~* "wordpress_logged_in_"){
    set $no_cache 1;
}

但是,这意味着在使用 PHPSESSID cookie 时请求的帖子页面(我的大部分点击)不会被缓存。帖子页面不包含每个用户的上下文并且是通用的。有没有更好的方法只允许缓存帖子页面?也许使用“domain.com/yyyy/mm/dd/post-name”模式?

【问题讨论】:

    标签: wordpress nginx caching


    【解决方案1】:

    这是我通常用来专门为 Wordpress/Woocommerce 网站禁用 Fast-CGI 缓存的块,它可能会有所帮助:

    #disabler
    set $no_cache 0;
    
    # POST requests and urls with a query string should always go to PHP
    if ($request_method = POST) {
        set $no_cache 1;
    }
    if ($request_method = PATCH) {
        set $no_cache 1;
    }
    if ($query_string != "") {
        set $no_cache 1;
    }   
    
    # Don't cache uris containing the following segments
    if ($request_uri ~* "/wp-admin/|/wp-login/|/xmlrpc.php|index.php|phpmyadmin|sitemap(_index)?.xml|sitemap$") {
        set $no_cache 1;
    }   
    if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
        set $no_cache 1;
    }
    if ($request_uri ~* "(/wp-admin/|/cart/|/checkout/|/account/|/mon-compte/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
        set $no_cache 1;
    }
    
    # Don't use the cache for logged in users or recent commenters
    if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in|postpass|wordpress_n$") {
        set $no_cache 1;
    }
    
    # Woocommerce
    if ($request_uri ~* "/store.*|/cart.*|/my-account.*|/checkout.*|/addons.*|/panier.*|/paiement.*|/mon-compte.*") {
        set $no_cache 1;
    }
    
    if ( $arg_add-to-cart != "" ) { 
       set $no_cache 1;
    }
    
    # need more tests
    #if ( $cookie_woocommerce_items_in_cart != "0" ) {  
    #   set $no_cache 1;
    #}
    
    if ( $cookie_woocommerce_items_in_cart ) {
        set $no_cache 1;
    }
    

    这是我找到的多篇文章和 Gist 的汇总。请注意,我通常在每个块中添加标头以查看在测试期间禁用缓存的是什么。有些规则可能重复。

    注销后,用户仍有一些 cookie,因此有时会绕过缓存。但它在大多数情况下都能正常工作。

    当然,实现全部或部分内容需要测试。

    我在Wordpress Nginx Helper 插件中使用它,这对于全局和条件清除非常有用。

    【讨论】:

      猜你喜欢
      • 2016-02-24
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 2018-03-04
      相关资源
      最近更新 更多