WP Rocket Nginx + Varnish Full Stabil Dengan Default Vhost CloudPanel

A. Default CloudPanel

Konfigurasi default cloudpanel tanpa wp rocket [sumber]

visitor > cloudflare > nginx 443 > varnish 6081 > nginx 8080 > php > redis > mariadb

B. Default Cloudpanel + WP Rocket

Konfigurasi default cloudpanel + wp rocket, php bekerja melalui aturan wp rocket advanced-cache.php, full stabil dan minim resiko error.

visitor > cloudflare > nginx 443 > varnish 6081 > nginx 8080 > php > wp rocket > redis > mariadb
server {
  listen 80;
  listen [::]:80;
  listen 443 quic;
  listen 443 ssl;
  listen [::]:443 quic;
  listen [::]:443 ssl;
  http2 on;
  http3 on;
  {{ssl_certificate_key}}
  {{ssl_certificate}}
  server_name domain.com;
  return 301 https://www.domain.com$request_uri;
}

server {
  listen 80;
  listen [::]:80;
  listen 443 quic;
  listen 443 ssl;
  listen [::]:443 quic;
  listen [::]:443 ssl;
  http2 on;
  http3 on;
  {{ssl_certificate_key}}
  {{ssl_certificate}}
  server_name www.domain.com www1.domain.com;
  {{root}}

  {{nginx_access_log}}
  {{nginx_error_log}}

  if ($scheme != "https") {
    rewrite ^ https://$host$request_uri permanent;
  }

  location ~ /.well-known {
    auth_basic off;
    allow all;
  }

  {{settings}}

  location ~/\.git {
    deny all;
  }

  location ~/(wp-admin/|wp-login.php) {
    #auth_basic "Restricted Area";
    #auth_basic_user_file /home/site-user/.htpasswd;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8080;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      7200;
    proxy_send_timeout         7200;
    proxy_read_timeout         7200;
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_temp_file_write_size 256k;
  }

  location / {
    {{varnish_proxy_pass}}
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_hide_header X-Varnish;
    proxy_redirect off;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      720;
    proxy_send_timeout         720;
    proxy_read_timeout         720;
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_temp_file_write_size 256k;
  }

  location ~* ^.+\.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map)$ {
    # WordPress Multisite Subdirectory
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 break;
    rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 break;
    add_header Access-Control-Allow-Origin "*";
    add_header alt-svc 'h3=":443"; ma=86400';
    expires max;
    access_log off;
  }

  if (-f $request_filename) {
    break;
  }
}

server {
  listen 8080;
  listen [::]:8080;
  server_name www.domain.com www1.domain.com;
  {{root}}

  include /etc/nginx/global_settings;

  try_files $uri $uri/ /index.php?$args;
  index index.php index.html;

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    try_files $uri =404;
    fastcgi_read_timeout 3600;
    fastcgi_send_timeout 3600;
    fastcgi_param HTTPS "on";
    fastcgi_param SERVER_PORT 443;
    fastcgi_pass 127.0.0.1:{{php_fpm_port}}; # PHP > WP Rocket
    fastcgi_param PHP_VALUE "{{php_settings}}";
  }

  # WordPress Multisite Subdirectory
  if (!-e $request_filename) {
    rewrite /wp-admin$ https://$host$uri permanent;
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;
    rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 last;
  }

  if (-f $request_filename) {
    break;
  }
}

Contoh penerapan scf.web.id

C. Oprek CloudPanel + WP Rocket Bypass PHP

Konfigurasi ekstrim, wordpress rasa web static, nginx rocket / bypass php.

Note : Status Eksperimental

visitor > cloudflare > nginx 443 > varnish 6081 > nginx 8080 > wp rocket > php > redis > mariadb

Konfigurasi WP rocket di blok server 8080

server {
  listen 8080;
  listen [::]:8080;
  server_name www.domain.com www1.domain.com;
  {{root}}

  include /etc/nginx/global_settings;

# ==========================================================
# Nginx 8080 > WP Rocket > PHP
# ==========================================================

# Path Cache WP Rocket
set $wpr_cache_file "/wp-content/cache/wp-rocket/$host$request_uri/index-https.html";
set $scf_bypass 0;

# Bypass Cookies
if ($request_method = POST) { set $scf_bypass 1; }
if ($args) { set $scf_bypass 1; }
if ($http_cookie ~* "(comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in|woocommerce_items_in_cart|wp_woocommerce_session_)") {
    set $scf_bypass 1;
}

# Eksekusi Bypass
if ($scf_bypass = 1) {
    set $wpr_cache_file "/bypass-cache-scf";
}

# Debug
add_header X-Cache-Engine "Ekstrim-SCF-Cache";

# Nginx 8080 > WP Rocket
location / {
    try_files $wpr_cache_file $uri $uri/ /index.php?$args;
}

# ==========================================================
# Nginx 8080 > WP Rocket > PHP
# ==========================================================

  # Jalur Default Nginx 8080 > PHP
  # try_files $uri $uri/ /index.php?$args;
  index index.php index.html;

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    try_files $uri =404;
    fastcgi_read_timeout 3600;
    fastcgi_send_timeout 3600;
    fastcgi_param HTTPS "on";
    fastcgi_param SERVER_PORT 443;
    fastcgi_pass 127.0.0.1:{{php_fpm_port}};
    fastcgi_param PHP_VALUE "{{php_settings}}";
  }

  # WordPress Multisite Subdirectory
  if (!-e $request_filename) {
    rewrite /wp-admin$ https://$host$uri permanent;
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;
    rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 last;
  }

  if (-f $request_filename) {
    break;
  }
}

Tambahan modul mu-plugins di wp-content

# ==========================================================
# /wp-content/mu-plugins/bypass-cache-cokies.php
# ==========================================================

<?php

add_action( 'send_headers', function() {
    $has_personal_cookie = false;
    foreach ( $_COOKIE as $key => $value ) {
        if ( preg_match( '/(wordpress_logged_in_|comment_author_|wp-postpass_|woocommerce_items_in_cart|wp_woocommerce_session_)/', $key ) ) {
            $has_personal_cookie = true;
            break;
        }
    }

    if ( is_user_logged_in() || $has_personal_cookie || is_admin() ) {
        header( 'Cache-Control: no-cache, must-revalidate, max-age=0, no-store, private' );
        header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
    }
});

add_filter( 'comment_form_default_fields', function( $fields ) {
    $fields['author'] = preg_replace( '/value="[^"]*"/', 'value=""', $fields['author'] );
    $fields['email']  = preg_replace( '/value="[^"]*"/', 'value=""', $fields['email'] );
    $fields['url']    = preg_replace( '/value="[^"]*"/', 'value=""', $fields['url'] );
    return $fields;
});

add_filter( 'show_comment_cookies_notice', '__return_false' );

add_action( 'wp', function() {
    if ( function_exists( 'is_woocommerce' ) ) {
        if ( is_cart() || is_checkout() || is_account_page() ) {
            header( 'Cache-Control: no-cache, must-revalidate, max-age=0, no-store, private' );
        }
    }
}, 1 );

# ==========================================================
# /wp-content/mu-plugin/bypass-cache-cokies.php
# ==========================================================

Penyesuaian default.vcl

cl 4.0;

import std;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
    .first_byte_timeout = 600s;
}

acl purger {
    "localhost";
    "127.0.0.1";
    "172.17.0.1";
}

sub vcl_recv {
    if (req.restarts > 0) {
        set req.hash_always_miss = true;
    }

    #return (pass);

    if (req.method == "PURGE") {
        if (client.ip !~ purger) {
            return (synth(405, "Method not allowed"));
        }
        if (req.http.X-Cache-Tags) {
          ban("obj.http.X-Cache-Tags ~ " + req.http.X-Cache-Tags);
        } else {
          ban("req.http.host == " +req.http.host+" && req.url ~ "+req.url);
          return (synth(200, "Purged"));
        }
        return (synth(200, "Purged"));
    }

    if (req.method != "GET" &&
        req.method != "HEAD" &&
        req.method != "PUT" &&
        req.method != "POST" &&
        req.method != "TRACE" &&
        req.method != "OPTIONS" &&
        req.method != "DELETE") {
          /* Non-RFC2616 or CONNECT which is weird. */
          return (pipe);
    }

    # We only deal with GET and HEAD by default
    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    # Set initial grace period usage status
    set req.http.grace = "none";

    # normalize url in case of leading HTTP scheme and domain
    set req.url = regsub(req.url, "^http[s]?://", "");

    # collect all cookies
    std.collect(req.http.Cookie);

    if (req.url ~ "^/admin/" || req.url ~ "/paypal/") {
        return (pass);
    }
     
    # Default Cloudpanel
    # if (req.http.cookie ~ "wordpress_logged_in_") {
    #   return (pass);
    # }
    
    # Bypass Cookies
    if (req.http.cookie ~ "wordpress_logged_in_|comment_author_|wp-postpass_|woocommerce_items_in_cart|wp_woocommerce_session_") {
    return (pass);
    }

    if (req.http.Accept-Encoding) {
        if (req.url ~ "\.(jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf|flv)$") {
            # No point in compressing these
            unset req.http.Accept-Encoding;
        } elsif (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
        } elsif (req.http.Accept-Encoding ~ "deflate" && req.http.user-agent !~ "MSIE") {
            set req.http.Accept-Encoding = "deflate";
        } else {
            # unknown algorithm
            unset req.http.Accept-Encoding;
        }
    }

    if (req.url ~ "(\?|&)(gclid|cx|ie|cof|siteurl|zanpid|origin|fbclid|mc_[a-z]+|utm_[a-z]+|_bta_[a-z]+)=") {
        set req.url = regsuball(req.url, "(gclid|cx|ie|cof|siteurl|zanpid|origin|fbclid|mc_[a-z]+|utm_[a-z]+|_bta_[a-z]+)=[-_A-z0-9+()%.]+&?", "");
        set req.url = regsub(req.url, "[?|&]+$", "");
    }

    if (req.http.Authorization ~ "^Bearer") {
        return (pass);
    }

    return (hash);
}

sub vcl_hash {
    if (req.http.host) {
        hash_data(req.http.host);
    } else {
        hash_data(server.ip);
    }
}

sub vcl_backend_response {

    # Bypass Cache
    if (beresp.http.Cache-Control ~ "private" || beresp.http.Cache-Control ~ "no-cache" || beresp.http.Cache-Control ~ "no-store") {
    set beresp.ttl = 0s;
    set beresp.uncacheable = true;
    return (deliver);
    }   

    set beresp.grace = 3d;

    if (beresp.http.content-type ~ "text") {
        set beresp.do_esi = true;
    }

    if (beresp.http.content-type ~ "text") {
        set beresp.do_gzip = true;
    }

    # cache only successfully responses and 404s that are not marked as private
    if (beresp.status != 200 && beresp.status != 404 && beresp.http.Cache-Control ~ "private") {
        set beresp.uncacheable = true;
        set beresp.ttl = 86400s;
        return (deliver);
    }

    # validate if we need to cache it and prevent from setting cookie
    if (beresp.ttl > 0s && (bereq.method == "GET" || bereq.method == "HEAD")) {
        unset beresp.http.set-cookie;
    }

   if (!beresp.http.cache-control) {
       set beresp.ttl = 0s;
       set beresp.uncacheable = true;
   }

    return (deliver);
}

sub vcl_deliver {

    set resp.http.X-Cache-Age = resp.http.Age;
    unset resp.http.Age;

    # Avoid being cached by the browser.
    if (resp.http.Cache-Control !~ "private") {
      set resp.http.Pragma = "no-cache";
      set resp.http.Expires = "-1";
      set resp.http.Cache-Control = "no-store, no-cache, must-revalidate, max-age=0";
    }

    unset resp.http.X-Powered-By;
    unset resp.http.Server;
    unset resp.http.X-Varnish;
    unset resp.http.Via;
    unset resp.http.Link;
    unset resp.http.X-Frame-Options;
    unset resp.http.X-Content-Type-Options;
    unset resp.http.X-Xss-Protection;
    unset resp.http.Referer-Policy;
    unset resp.http.X-Permitted-cross-domain-policies;
}

sub vcl_hit {
    if (obj.ttl >= 0s) {
        return (deliver);
    }
    set req.http.grace = "unlimited (unhealthy server)";
    return (deliver);
}

Contoh penerapan / wordpress uji wp.scf.my.id

Hapus Cache WP Rocket + Varnish + Cloudflare

Agar penghapusan cache sinkron, aktifkan add on di wp rocket untuk cloudflare dan varnish, lalu instal juga plugin pembantu wp rocket WP Rocket | Varnish IP. Tidak perlu instal plugin CLP Varnish Cache karena tugas pembersihan cache varnish sudah sinkron saat klik wp rocket clear cache.

Edit plugin WP Rocket | Varnish IP dan tambahakan port :6081 ke belakang IP 127.0.0.1

<?php
/**
 * Plugin Name: WP Rocket | Varnish IP
 * Description: Sets a custom Varnish IP to sync WP Rocket’s cache with.
 * Plugin URI:  https://github.com/wp-media/wp-rocket-helpers/tree/master/compatibility/wp-rocket-compat-varnish-ip/
 * Author:      WP Rocket Support Team
 * Author URI:  http://wp-rocket.me/
 * License:     GNU General Public License v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Copyright SAS WP MEDIA 2018
 */

namespace WP_Rocket\Helpers\compat\varnish_ip;

// Standard plugin security, keep this line in place.
defined( 'ABSPATH' ) or die();

/**
 * Return custom Varnish IP
 *
 * @author Arun Basil Lal
 *
 * @param (array) $ips Array containing custom Varnish IP's
 * @return array
 */
function set_custom_varnish_ip( $ips ) {

	if ( ! is_array( $ips ) ) {
        	$ips = (array) $ips;
    	}

	$ips[] = '127.0.0.1:6081';	// Enter your custom Varnish IP here
	// $ips[] = '13.1.2.3:23457';	// Add each new IP as a new line, you can add the port if needed
	
	return $ips;
}
add_filter( 'rocket_varnish_ip', __NAMESPACE__ . '\set_custom_varnish_ip' );

Tinggalkan komentar