Enable LiteSpeed Cache Module
Before using any rewrite rules to enable cache in .htaccess, you will need to register/configurate cache module and setup cache root. Please refer this article to learn how to enable LiteSpeed Cache module if you have not done so.
Using Rewrite Rules with E=cache-control
Rewrite rules can be placed in a directory’s .htaccess
file. The difference between using rewrite rules through E=cache-control
is that a rewrite rule can control the cache expiration (TTL).
Here’s a simple example using a rewrite rule to set up public caching of the entire site for 2 minutes:
RewriteEngine On
RewriteCond condition1
RewriteRule .* - [E=cache-control:max-age=120]
Note that there is no need to specify “public” because that is the default. Also, caching time is in seconds (i.e. use 120 seconds to cache for 2 minutes).
Here’s a simple example using a rewrite rule to disable cache:
RewriteEngine On
RewriteCond condition4
RewriteRule .* - [E=Cache-Control:no-cache]
Here’s a simple example using a rewrite rule to set up private cache:
RewriteEngine On
RewriteCond condition3
RewriteRule .* - [E=cache-control:private]
Note that there is no need to specify the max-age for private cache since it is for a specific browser and is controlled by the session.
Examples of LSCache Rewrite Rules
Example 1: Rewrite Rules Only
Enable cache and cache everything for 2 minutes:
<IfModule LiteSpeed>
RewriteEngine On
RewriteRule (.*\.php)?$ - [E=cache-control:max-age=120]
</IfModule>
Example 2: Rewrite Rules Only
<IfModule LiteSpeed>
RewriteEngine On
## cache should be available for HEAD or GET requests
RewriteCond %{REQUEST_METHOD} ^HEAD|GET$
## select which pages to cache
RewriteCond %{HTTP_COOKIE} page_contain_cachetoken=yes
# with other condition
RewriteCond %{QUERY_STRING} !s=[a-fA-F0-9]{32}
# excluding certain URLs
RewriteCond %{REQUEST_URI} !/(login|register|usercp|private|profile|cron|image)\.php$
# cache for 2 mins for php pages only
RewriteRule /(.*\.php)?$ - [E=Cache-Control:max-age=120]
</IfModule>
<IfModule LiteSpeed>
# for those not met above condition, enable private cache.
RewriteCond %{REQUEST_METHOD} ^HEAD|GET$
## select which pages to serve from private cache
RewriteCond %{HTTP_COOKIE} !page_contain_cachetoken=yes
# with other condition
RewriteCond %{QUERY_STRING} !s=[a-fA-F0-9]{32}
# excluding certain URLs
RewriteCond %{REQUEST_URI} !/(login|register|usercp|private|profile|cron|image)\.php$
# private cache for however long set in cache policy for php pages only
RewriteRule (.*\.php)?$ - [E=Cache-Control:max-age=120]
RewriteRule (.*\.php)?$ - [E=Cache-Control:private]
</IfModule>
These rules can be placed in one of the following 2 locations:
.htaccess
(last line needs to changed as follows:)- LiteSpeed native configuration: Web Admin Console > Configurations > Virtual Hosts > Rewrite
Restart LSWS to make changes effective.
Any time thre is a change on .htaccess
or the WebAdmin console, you will need to restart LSWS. Admin Console > Actions > Graceful Restart or run /path/to/lsws/bin/lswsctrl restart
or service lsws restart
from the command line.
Verify Caching is Working
Open your browser’s inspector, by right-clicking and selecting Inspector or pressing the F12 key, and refresh the page. Under the Network tab, look for the HTML page you just loaded and click on it to view its response header.
In the response header you should see X-LiteSpeed-Cache: hit
to indicate that the page was served from cache successfully. If you see X-LiteSpeed-Cache: miss
, reload the page and check again.
Notes
OpenLiteSpeed outputs a response header X-LiteSpeed-Cache: hit
if a request is served from public cache.
OpenLiteSpeed outputs a response header X-LiteSpeed-Cache: hit,private
if a request is served from private cache.
The LSCache hit rate is calculated based on all files served. Many of the files served by LSWS, like CSS or HTML, are intentionally not cached by LSCache. Because these files are included in the LSCache hit rate calculation, the hit rate may sometimes look much lower than one might expect.
You will not see a Cache-Control:max-age
header when you use LSCache. Please be aware there are two different concepts: Cache-Control:max-age
is a browser cache header. It is not for server-side cache. x-litespeed-cache-control: public,max-age=86400
is an LSCache control header, which will be seen when the cache plugin being used. When using a rewrite rule like [E=cache-control:max-age=120]
to enable cache as instructed in this wiki, you won’t see the x-litespeed-cache-control
header.
Cache Purge
OpenLiteSpeed will delete expired cache files automatically, making this step optional. Assuming you have a need to manually delete the outdated files, you can choose one of the following ways:
Linux Command via Cron
A cron job should be set to clear out old cache files that are past the set Time To Live (TTL).
To do this, you should run the crontab either as the root user or as the cache owner for self-management.
crontab -e
The virtual host cache root directory is normally located in /usr/local/lsws/cachedata
*/10 * * * * root find /virtualhost/cache/root/directory/ -type f -mmin +8 -delete 2>/dev/null
Note: This cron job deletes cached files that are more than 8 minutes old every 10 minutes. Since the cache TTL is set at 120 seconds (2 minutes), it is safe to delete these files as they are way past their TTL.
By URL via PHP Script
You can create a PHP script to do purge the cache by URL.
Usage: php $argv[0] -(r|p) domain url [server_ip] [port]
-r method option: Refresh cache (use stale cache while updating cache)
-p method option: Purge cache (delete cache entry)
domain: required parameter for domain name
url: required parameter for url
server_ip: optional parameter, default is 127.0.0.1
server_port: optional parameter, default is 80
Example 1:
/usr/local/lsws/admin/fcgi-bin/admin_php5 /usr/local/lsws/admin/misc/purge_cache_byurl.php -r mywebsite.com /index.php
Example 2:
/usr/local/lsws/admin/misc>php purge_cache_byurl.php -p www.domain.com /
HTTP/1.0 200 Purged
Date: Wed, 03 Jun 2015 05:48:31 GMT
Server: LiteSpeed
Connection: close
Note 1: The required URL has to be a //specific// URL and can not include wildcards, otherwise it may return 400 – Bad request error. Alternately, if you want to delete all cached files, you can do it through OS command, e.g.: rm -rf /lsws-cache-folder*
Note2: Server_ip
can not be omitted in some cases!
The PHP script code:
<?php
/****
* purge_cache_byurl
*
* Example: /usr/local/lsws/admin/fcgi-bin/admin_php5 /usr/local/lsws/admin/misc/purge_cache_byurl.php -r mywebsite.com /index.php
*/
if ($argc < 4 || $argc > 6) {
echo "Invalid arguments!\n";
echo "Usage: php $argv[0] -(r|p) domain url [server_ip] [port]
-r method option: Refresh cache (use stale cache while updating cache)
-p method option: Purge cache (delete cache entry)
domain: required parameter for domain name
url: required parameter for url
server_ip: optional parameter, default is 127.0.0.1
server_port: optional parameter, default is 80
";
exit;
}
if ( $argv[1] == '-p' )
$method = "PURGE";
else if ($argv[1] == '-r' )
$method = "REFRESH";
else
{
echo "ERROR: unknown or missing method option";
exit;
}
$domain = $argv[2];
$url = $argv[3];
$server_ip = ($argc >= 5) ? $argv[4] : '127.0.0.1';
$port = ($argc == 6) ? $argv[5] : 80;
$fp = fsockopen($server_ip, $port, $errno, $errstr, 2);
if (!$fp) {
echo "$errstr ($errno)\n";
} else {
$out = "$method $url HTTP/1.0\r\n"
. "Host: $domain\r\n"
. "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
Please refer to the LiteSpeed wiki for more instructions.
Rewrite Rule Examples
By Application
If you are running WordPress, Joomla! 3, Drupal 8, Mediawiki, or any other site for which we have cache plugins available, you should NOT follow this wiki. Instead, your plugins should be installed and configured by following the related articles.
General Examples
If none of above applications are being used, please refer the following general rewrite examples.
Cache Everything for 2 Minutes (Simple!)
<IfModule LiteSpeed>
RewriteEngine On
RewriteRule cacheablefolder/(.*\.php)?$ - [E=cache-control:max-age=120]
</IfModule>
Note: Only cache *.php
files in the cacheablefolder
directory. As pointed out previously, it is a good practice to cache only the files that are supposed to be cached.
Only Cache Pages That Have a Certain Signature
Note: %{ORG_REQ_URI}
is a LiteSpeed-specific variable. In this case, it keeps the value of %{REQUEST_URI}
prior to the rewrite to index.php
in the first part.
# this part is for public cache.
<IfModule LiteSpeed>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^HEAD|GET$
RewriteCond %{HTTP_COOKIE} !cookiename ## cookiename needs to be replaced by real cookie name
RewriteCond %{ORG_REQ_URI} !^/administrator
RewriteRule .* - [E=Cache-Control:max-age=300]
</IfModule>
#application orgiginal rewite rules
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php [L]
This example demonstrates how LSCache rewrite rules fit in an application’s rewrite rules. The first part is from the application (such as Joomla). Essentially everything goes through index.php
(the Joomla framework) to process.
The first part of the ruleset indicates that LSWS only caches requests if the following is true:
- they are HEAD or GET type requests
- they don’t contain
loginuser
in theHTTP_COOKIE
%{ORG_REQ_URI}
is not/index.php
%{ORG_REQ_URI}
does not start with/administrator/
%{ORG_REQ_URI}
ends with.php
or.html
or.htm
, etc.
The TTL of the cache is 300 seconds (5 minutes).
Private Cache
<IfModule LiteSpeed>
# this part is for private cache, note that HTTP_COOKIE is for loginuser
RewriteCond %{REQUEST_METHOD} ^HEAD|GET$
RewriteCond %{HTTP_COOKIE} loginuser
RewriteCond %{ORG_REQ_URI} !^/index\.php$
# there is no need to exclude admin area. it can be private cached.
# RewriteCond %{ORG_REQ_URI} !^/administrator/
RewriteRule .* - [E=Cache-Control:private]
</IfModule>
or
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$ [NC]
RewriteRule (.*) index.php [L]
This ruleset indicates that LSWS only privately caches requests if they
- are HEAD and GET type requests
- DO contain loginuser in the
HTTP_COOKIE
%{ORG_REQ_URI}
is not/index.php
%{ORG_REQ_URI}
ends with.php
or.html
or.htm
, etc.
The TTL of the cache is however long the cache policy indicates.
Disable Caching When Private Caching is Enabled
While it is not recommended to have private caching enabled in the cache policy, doing so enables private caching for all domains/vhosts. However, certain domains/vhosts may not work well when private cache is on by default. In this case, we need to disable private caching for those domains/vhosts.
To do so:
- Purge the private cache copy if it is still valid(fresh).
- Put the following entry in .htaccess` under the document root of the domain/virtual host in question.
<IfModule LiteSpeed>
RewriteEngine On
RewriteRule .* - [E=Cache-Control:no-cache]
</IfModule>
Enable Cache for Mobile View
Set up a different cache copy for mobile view through cache vary. Also exclude some folders from cache, then cache everything else:
<IfModule LiteSpeed>
RewriteEngine On
CacheDisable public /
RewriteCond %{HTTP_USER_AGENT} "iPhone|iPod|BlackBerry|Palm|Mobile|Opera Mini|Fennec|Windows Phone"
RewriteRule .* - [E=Cache-Control:vary=ismobile]
RewriteCond %{REQUEST_METHOD} ^HEAD|PURGE|GET$
RewriteCond %{ORG_REQ_URI} !/news
RewriteCond %{ORG_REQ_URI} !/admincp
RewriteRule .* - [E=Cache-Control:max-age=120]
</IfModule>