Last active
September 19, 2021 09:20
-
-
Save idokd/5599daa42c3df58435f8ae84ce0acef1 to your computer and use it in GitHub Desktop.
WP Rocket Cache Purge / Invalidation with GCP Cloud CDN - Load Balancer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Make sure that you have gcloud installed on server, and is accesible with the proper permissions to httpd/apache/ngix | |
| // Update this variable with the GCP Cloud CDN Load Balancer name, or set it via filter: gcp_cloud_cdn_urlmap | |
| define( 'GCP_CLOUD_CDN_URLMAP', 'your-load-balancer-id-goes-here' ); | |
| add_action( 'after_rocket_clean_home', 'gcp_cloud_cdn_invalidate_cdn_cache_home', 100 ); | |
| add_action( 'after_rocket_clean_domain', 'gcp_cloud_cdn_invalidate_cdn_cache_domain', 100 ); | |
| add_action( 'after_rocket_clean_cache_dir', 'gcp_cloud_cdn_invalidate_cdn_cache', 100 ); | |
| add_action( 'after_rocket_clean_file', 'gcp_cloud_cdn_invalidate_cdn_cache', 100 ); | |
| function gcp_cloud_cdn_invalidate_cdn_cache_domain() { | |
| gcp_cloud_cdn_invalidate_cdn_cache( '/*' ); | |
| } | |
| function gcp_cloud_cdn_invalidate_cdn_cache_home() { | |
| gcp_cloud_cdn_invalidate_cdn_cache( '/' ); | |
| } | |
| function gcp_cloud_cdn_invalidate_cdn_cache( $param = null ) { | |
| $urlmap = apply_filters( 'gcp_cloud_cdn_urlmap', defined( 'GCP_CLOUD_CDN_URLMAP' ) ? GCP_CLOUD_CDN_URLMAP : null ); | |
| if ( !$urlmap ) return; | |
| $parts = parse_url( site_url() ); | |
| $domain = apply_filters( 'gcp_cloud_cdn_urlmap_domain', $parts[ 'host' ] ); | |
| $paths = []; | |
| if ( is_array( $param ) ) { | |
| foreach( $param as $path ) $paths[] = str_replace( site_url(), '', $path ); | |
| } else if ( $param ) { | |
| $paths[] = str_replace( site_url(), '', $param ); | |
| } | |
| foreach ( $paths as $path ) { | |
| $clean = 'gcloud compute url-maps invalidate-cdn-cache ' . $urlmap . ' --async --host "' . $domain . '" --path "' . $path . '" > /dev/null &'; | |
| exec( $clean ); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script is intended to resolve issues when you use WP-Rocket behind a GCP Cloud CDN (using Load Balancer) and require to purge the cached files from the CDN.
WP-Rocket doesn't support the GCP Cloud CDN yet, and unfortunately, the GCP Cloud CDN invalidate doesn't support API so only a gcloud command works at the moment, so it is required to have it on the VMs with sufficient permission to the apache/httpd user.