Webstuff.Inblighty.Com

Website DIY - tricks and solutions

WP Rocket: Geolocation and caching by country

You can view and download the code from Github. Its been tested by various users without incident – but use at your own risk it might ruin your site. At some point I may submit the code for inclusion in WordPress.org’s plugin directory.

Special thanks to Pieter Boss for i18n work on this plugin. Do what you want with the source but please credit myself and Pieter in any code you develop.

Documentation (a work in progress).

The Country Caching for WP Rocket (CC4R) plugin:


1. Installation


1. Install plugin.

2. Dashboard->Settings->WP Rocket Country Caching and tick “Enable” to start Country Caching. (However you will probably want to select other settings as well.)

Caveat: I’ve not had problems; but do not test unless you can fix problems outside of WordPress (white screen of death issues frequently appear on caching support forums).

cc caching options


Multisite:

CC4R settings are accessible via the Network Admin dashboard (Network Dashboard->WP Rocket Country Caching)

Note 1: due to WP Rocket design the SAME country caching (CC4R) settings will be applied to ALL your sites.

Note 2: WP Rocket does not use .htaccess mod-rewrites in Multisite environments, consequently the CC4R rewrite option is also unavailable.


2. More Information:






2.1. Modify Rocket Rewrites option


Enabling this option is recommended. If you find enabling conflicts (it shouldn’t) with your site’s other plugins, or Rocket settings, then turn option off.

cc caching options

More information on Rocket Performance and this option here.


 


2.2. Optional Settings to reduce caching overheads


These examples refer to the field numbers in Fig. 1 below):

i. Default – create a separate cache for every country from which site has had a visitor:

Leave [field 1] empty, and ensure [field 2] is NOT checked.

ii. All visitors to see site’s standard content except visitors from: e.g. France,Canada and Spain who see custom content.

Enter FR,CA,ES in [field 1] and ensure [field 2] is NOT checked.

Fig 1. Settings for example iv. (below)
cc caching options
Fig 1. Settings for example iv. (below)

iii. Just one Group, and one Standard (non-group) cache. Example: European Union countries and non-EU countries.

Enter “XX” (a non existent country never cached) in [field 1]. Ensure [field 2] is checked. Enter country codes for your group in [field 3] e.g. EU country codes.

iv. Some countries individually cached, a single cache for a group of countries, and a standard cached page for everyone else. Fig 1 above.

Fig 1 example. Site serves different Amazon adverts based on country (Japan=Amazon.jp, GB & Ireland= co.uk; rest of EU= .de, all others= .com). Additionally if a visitor is from the EU a Cookie Compliance plugin is run and notice displayed. Enter GB,IE,JP in [field 1], ensure [field 2] is checked; and insert EU countries in [Field 3]. N.B. it does not matter if you include GB & IE again – because they are listed in [field 1] they will be separately cached.

v. A single cache for specified list of countries; and all other countries to be individually cached.

Leave [field 1] empty. Ensure [field 2] is checked. Enter country codes for your group in [field 3].


 


2.3. GeoLocation method


cc caching options

i. Maxmind:

Should work with any server.

The look-up file was the latest version when you installed CC4R. It is located in “/wp-content/cca_maxmind_data/”. You can replace this as and when, with a new GeoLite2 Country from Maxmind’s download page.

Alternatively, if you are using the CCA plugin it will auto update the file each month (it uses the same “use Cloudflare or Maxmind” code, and shares the same Maxmind file).

ii. Cloudflare

Look-up used by many plugins. Fast, reliable. Ensure your Cloudflare Settings are set to default caching.

iii. Amazon

Fast. Ensure you set appropriate caching level on AWS/Cloudfront (I guess static content only). Not tested (I don’t use Amazon) – please let me know if it works for you.

iv. Other CDN/server header

Fast. Enter the $_SERVER variable and Http header name supplied by the provider. If a CDN ensure you’ve set its own caching appropriately.

cc other CDN options

In the case of Apache et al provided Geoip, your entry in “HTTP header name” should probably be the same as the $_SERVER variable name (as in above image).

In the case of 3rd party/CDN provided Geoip, then your server will likely provide a $_SERVER name that is an uppercase version of the Http Header Name with hyphens replaced by underscores and prefixed with “HTTP_” e.g. for Cloudflare the HTTP header name is “cf-IPCountry” and the $_SERVER variable name is “HTTP_CF_IPCOUNTRY”.

You can view your sites Http Header and Sever variables via CC4R’s “CC Info” tab.

display HTTP header and Server Vars

v. Connect to other plugin

Ask plugin author to add the filter it’s in his interest to make her plugin Rocket compatible. Or add your own filter to your own site-specific plugin or “functions.php”.

The filter should return either a 2 character country ISO code or “error”. Example:


function cc4wpr_get_plugin_country() {
    $2charISOcode = "error";
    if ( function_exists('somegeo_function_forisoCode') ) {
      $2charISOcode = somegeo_function_forisoCode();
    }
    return $2charISOcode;
}
add_filter('cc_use_other_geoip', 'cc4wpr_get_plugin_country')


 


2.4. Geolocation compatibility, speed, accuracy


If you don’t specify a geolocation system then either Cloudflare (if available) or Maxmind’s country lite database (auto downloaded from Maxmind at the time you installed CC4R) is automatically used.

Compatibility between plugins:

For many sites displaying custom content by country the odd discrepancy is acceptable and CC4R’s default geolocation will be fine. If not, CC4R allows you to plug in the geolocation of your choice.

Discrepancies: there may be edge cases (1/1000 ?) where your plugin for country content identifies a different location than (default) CC4R. For example when using Opera VPN browser to “spoof” location, Cloudflare identifies me as from “XX” (unknown) but Litespeed as from France. There may also be rare discrepancies if your country plugin uses an older or newer copy of Maxmind’s DB.

N.B. Many decent WP plugins default to Cloudflare for compatibility. So if you have enabled Cloudflare Country chances of compatibility are high.

Geolocation and speed:

(Simplistically, this only applies to the first ever page requested by a new visitor.)

Using Cloudflare/Amazon/other header to obtain the visitor country code should result in slightly faster performance than using a plugin’s own look-up.

If you don’t use one of the above then a new visitor will be served an un-cached first page and CC4r or your geo plugin has to process the look-up.

Accuracy:

Maxmind: updates its Country Lite DB file monthly and claims 99.8% accuracy. I assume CDNs have a similar level of accuracy.

N.B. most plugins using Maxmind do not auto-update the DB file, so geolocation will be less accurate. It is possible to auto-update Maxmind for CC4R.

Country from Server Headers: Typically generated from a now obsolete Maxmind (Legacy) look-up file last updated in April 2018. Server libraries do exist to use current Maxmind2 data, and it was added as an option in last months (Aug 2018) release of (Apache clone) Litespeed. However my shared Litespeed server still uses out of date Maxmind Legacy.

 


2.5. Performance


Partial Draft (incomplete)

In an ideal world WP Rocket will modify web server settings (.htaccess) for optimum performance so that cached pages are accessed and served directly and faster without delay of running scripts and MySQL/DBMS.

cc caching options

With these optimum settings, if page “/some-page” is requested, and a cached copy already exists ("/cache-dir-path/some-page/index.html"), then it will be immediately served to the visitor without loading WordPress or DBMS.

However; some Rocket Settings e.g. “Separate cache files for mobile devices” and some plugins require different versions of the same page to be cached. WP Rocket has Helper Scripts for these plugins which tells Rocket how to handle page content.

Many of these Helpers disable fast rewrite. E.g. a “gender” plugin may tell Rocket i. always run WordPress do not use fast rewrites, ii. do not cache first visit (no gender cookie), iii. once a visitor has set a gender cookie cache and serve either “/cache-dir-path/some-page/index-male.html" or “/cache-dir-path/some-page/index-female.html".

cc caching options

With the CC4R rewrite option enabled: Unless another plugin has told Rocket to remove fast rewrites: then Rocket will modify .htaccess so it can handle the variety cache file names needed for country caching.

cc caching options

CC4R’s rewrite option should not conflict with other plugins or settings, but if it does you can simply switch the option off.

 


2.6. CCA (Category Country Aware) users


CCA uses the same Cloudflare/Maxmind look-up script as this plugin – so CC4R’s default geolocation settings will work perfectly. The CCA plugin will also update the Maxmind look-up file each month for you (both plugins share the same copy of Maxmind’s file).

Alternatively, if you now wish to use country code provided by an Amazon or other CDN header then for compatibility configure CCA to do this as well. At a later date these choices will be added as standard options in CCA’s own settings form.

 


2.7. Country Blocking Plugins


I am not a fan. Those blocking in WordPress provide zero protection against DDOS attacks and allow WP/plugin code to run leaving you exposed to attacks on “new” vulnerabilities. In support forums you will also see Admins reporting they can no longer access WordPress.

I’ve no idea if Country Caching is compatible with these plugins. HTACCESS is faster and safer; I might build htacccess blocking into CC4R; however the DIY solutions below are just as good, and CDN blocking better.

CDN’s such as Cloudflare and Amazon allow you to block countries before they even hit your site. Alternatively, if available, use CDN or server provided country header to block in your htacess.

Otherwise, you can paste blocking “code” from Country IP Blocks into your htaccess.


3. Testing


You can visit Locabrowser.com to simulate visiting (and caching) your site from different countries. Alternatively use a VPN: The (500MB free) Tunnelbear Extension for Chrome has options for 20 countries.

cc caching options

The CC Plugin includes a shortcode that may help testing. Add [cc4r_test_msg] to some posts or in a shortcode enabled widget such as CCA’s.

N.B. if you are not using a CDN/header; then you will be served an uncached page for the first ever page visited will. It will be cached on someonelse’s visit or your next visit to the page.

Cache files created by WP Rocket if CC4R is enabled:

WP Rocket creates a cache folder for each page and writes different cached versions of the page to that folder. Location: /wp-content/cache/wp-rocket/your-site-name/page-name

cache files created

With CC4R enabled and configured you will see cache files like the above in each pages folder. The naming of the cached files is dependent on what plugins you have installed. In the above example “CC4R” and “Cookie Notice for GDPR” are in use and configured for WP Rocket. If the above example:

  1. -https-” (yellow highlighted) identifies it as an HTTPS version of the page. If not present the cache is for an HTTP version.
  2. -true-” (red highlighted) if present indicates a version of the page for visitors who have consented to cookies.
  3. std”, or “cc_grp” or country code e.g. “GB“, “US” etc (blue highlighted). See 2.2 Optional Settings to reduce caching overheads above. “-cc_grp-” identifies the cache for the list of countries you specified should be cached as a group. “-std-” – if you identified specific countries, only, to be separately cached then all other countries (unless part of your group list) will share the same standard “-std-” cache.


Questions/Feedback


Just post a comment below. It would be useful if you provided an email address (not displayed) so I can contact you directly if necessary.



9 Comments

  1. Alexander

    This really looks promising. WP Rocket has not been able to integrate geo location for years and support posts date back to 2016 requesting it 😉

    I have used workarounds so far, which work on smaller sites, but building a unique cache per location is essential for bigger websites.

    Would love to take it for a spin.

    Regards
    Alex

  2. Yuri

    Hi!

    Does your plugin support PHP 7.2.* 7.3.* versions?

    • AW

      Unfortunately I don’t have a current WP Rocket licence. At the time I tested it worked under PHP7.1 and off the top of my head I don’t think the plugin uses anything likely to have been depracated under 7.2 and 7.3.

  3. Vitalij

    Some performance drop in pagespeed

    When is enabled, after time performance in google pagespeed is slowing down. About twicely.
    Test app does not see that files are combined into 1 file.

  4. An Nguyen

    Thanks, it’s working now!

  5. Dong

    How do we activate preloading when applying CC4R. The reason is WP Rocket standard preload will only work for default cache group. My site for example will have separate cache for VN, AU and the rest of the world. I couldnt find a way to activate preloading

    • AW

      Unfortunately I no longer have a license for WP-Rocket and it is a long time since I wrote the script. I suspect you will not be able to use country caching with Rockets own preload. It might be possible to write your own script to request every page as a visitor from these 3 locations effectively pre-creating 3 caches of all these pages. Additionally, you may also need to edit country caching to temporarily check for country using one of PHPs spoofable IP variables and use something like burpsuite to do the spoofing from your browser.

  6. Gabriel

    Hi,

    Thanks for the Plugin. I have a question.
    How can i verify if the plugin works on a file level? WP Rocket is saving the cached files on /wp-content/cache. Can you show me or explain where the plugin save the differing caches?

    Thanks in advance
    Gabriel

    • AW

      Hi Gabriel. I’ve added an explanation under “3. Testing” in the above post. Assuming CC4R is working correctly WP Rocket will now save additional cached versions of each page in its folder for each page.

      N.B. if your browser is logged in to your site then its requests will not create pages. If you change which countries are separately cached or grouped under CC4R, then it will delete cache files to ensure old and now incorrectly cached versions are not served.

      My Rocket license expired last year so I am no longer able to modify and test CC4R.

Leave a Reply to Alexander Cancel reply

Your comment will appear after its approved; usually within 12 hours but can be up to a week.
Email is optional and never published. It will only be used to contact you if clarification of your comment is needed.

Copyright © 2018-2024 Webstuff.Inblighty.Com
This site recommends and is hosted by: Kualo Web Hosting.    
Theme: hemingway
 

Blog home  |  ↑ Top of Page ↑