* The htaccess rewrite rule operation class
defined('WPINC') || exit();
class Htaccess extends Root {
private $frontend_htaccess = null;
private $_default_frontend_htaccess = null;
private $backend_htaccess = null;
private $_default_backend_htaccess = null;
private $theme_htaccess = null; // Not used yet
private $frontend_htaccess_readable = false;
private $frontend_htaccess_writable = false;
private $backend_htaccess_readable = false;
private $backend_htaccess_writable = false;
private $theme_htaccess_readable = false;
private $theme_htaccess_writable = false;
const LS_MODULE_START = '<IfModule LiteSpeed>';
const EXPIRES_MODULE_START = '<IfModule mod_expires.c>';
const LS_MODULE_END = '</IfModule>';
const LS_MODULE_REWRITE_START = '<IfModule mod_rewrite.c>';
const REWRITE_ON = 'RewriteEngine on';
const LS_MODULE_DONOTEDIT = '## LITESPEED WP CACHE PLUGIN - Do not edit the contents of this block! ##';
const MARKER = 'LSCACHE';
const MARKER_NONLS = 'NON_LSCACHE';
const MARKER_LOGIN_COOKIE = '### marker LOGIN COOKIE';
const MARKER_ASYNC = '### marker ASYNC';
const MARKER_CRAWLER = '### marker CRAWLER';
const MARKER_MOBILE = '### marker MOBILE';
const MARKER_NOCACHE_COOKIES = '### marker NOCACHE COOKIES';
const MARKER_NOCACHE_USER_AGENTS = '### marker NOCACHE USER AGENTS';
const MARKER_CACHE_RESOURCE = '### marker CACHE RESOURCE';
const MARKER_BROWSER_CACHE = '### marker BROWSER CACHE';
const MARKER_MINIFY = '### marker MINIFY';
const MARKER_CORS = '### marker CORS';
const MARKER_WEBP = '### marker WEBP';
const MARKER_DROPQS = '### marker DROPQS';
const MARKER_START = ' start ###';
const MARKER_END = ' end ###';
* Initialize the class and set its properties.
public function __construct() {
$this->_default_frontend_htaccess = $this->frontend_htaccess;
$this->_default_backend_htaccess = $this->backend_htaccess;
$frontend_htaccess = defined('LITESPEED_CFG_HTACCESS') ? constant('LITESPEED_CFG_HTACCESS') : false;
if ($frontend_htaccess && substr($frontend_htaccess, -10) === '/.htaccess') {
$this->frontend_htaccess = $frontend_htaccess;
$backend_htaccess = defined('LITESPEED_CFG_HTACCESS_BACKEND') ? constant('LITESPEED_CFG_HTACCESS_BACKEND') : false;
if ($backend_htaccess && substr($backend_htaccess, -10) === '/.htaccess') {
$this->backend_htaccess = $backend_htaccess;
// Filter for frontend&backend htaccess path
$this->frontend_htaccess = apply_filters('litespeed_frontend_htaccess', $this->frontend_htaccess);
$this->backend_htaccess = apply_filters('litespeed_backend_htaccess', $this->backend_htaccess);
// frontend .htaccess privilege
$test_permissions = file_exists($this->frontend_htaccess) ? $this->frontend_htaccess : dirname($this->frontend_htaccess);
if (is_readable($test_permissions)) {
$this->frontend_htaccess_readable = true;
if (is_writable($test_permissions)) {
$this->frontend_htaccess_writable = true;
$this->__rewrite_on = array(
'RewriteRule .* - [E=Cache-Control:no-autoflush]',
'RewriteRule ' . preg_quote(LITESPEED_DATA_FOLDER) . '/debug/.*\.log$ - [F,L]',
'RewriteRule ' . preg_quote(self::CONF_FILE) . ' - [F,L]',
// backend .htaccess privilege
if ($this->frontend_htaccess === $this->backend_htaccess) {
$this->backend_htaccess_readable = $this->frontend_htaccess_readable;
$this->backend_htaccess_writable = $this->frontend_htaccess_writable;
$test_permissions = file_exists($this->backend_htaccess) ? $this->backend_htaccess : dirname($this->backend_htaccess);
if (is_readable($test_permissions)) {
$this->backend_htaccess_readable = true;
if (is_writable($test_permissions)) {
$this->backend_htaccess_writable = true;
* Get if htaccess file is readable
private function _readable( $kind = 'frontend' ) {
if ($kind === 'frontend') {
return $this->frontend_htaccess_readable;
if ($kind === 'backend') {
return $this->backend_htaccess_readable;
* Get if htaccess file is writable
public function writable( $kind = 'frontend' ) {
if ($kind === 'frontend') {
return $this->frontend_htaccess_writable;
if ($kind === 'backend') {
return $this->backend_htaccess_writable;
* Get frontend htaccess path
public static function get_frontend_htaccess( $show_default = false ) {
return self::cls()->_default_frontend_htaccess;
return self::cls()->frontend_htaccess;
* Get backend htaccess path
public static function get_backend_htaccess( $show_default = false ) {
return self::cls()->_default_backend_htaccess;
return self::cls()->backend_htaccess;
* Check to see if .htaccess exists starting at $start_path and going up directories until it hits DOCUMENT_ROOT.
* As dirname() strips the ending '/', paths passed in must exclude the final '/'
private function _htaccess_search( $start_path ) {
while (!file_exists($start_path . '/.htaccess')) {
if ($start_path === '/' || !$start_path) {
if (!empty($_SERVER['DOCUMENT_ROOT']) && wp_normalize_path($start_path) === wp_normalize_path($_SERVER['DOCUMENT_ROOT'])) {
if (dirname($start_path) === $start_path) {
$start_path = dirname($start_path);
* Set the path class variables.
private function _path_set() {
$frontend = Router::frontend_path();
$frontend_htaccess_search = $this->_htaccess_search($frontend); // The existing .htaccess path to be used for frontend .htaccess
$this->frontend_htaccess = ($frontend_htaccess_search ?: $frontend) . '/.htaccess';
$backend = realpath(ABSPATH); // /home/user/public_html/backend/
if ($frontend == $backend) {
$this->backend_htaccess = $this->frontend_htaccess;
// Backend is a different path
$backend_htaccess_search = $this->_htaccess_search($backend);
// Found affected .htaccess
if ($backend_htaccess_search) {
$this->backend_htaccess = $backend_htaccess_search . '/.htaccess';
// Frontend path is the parent of backend path
if (stripos($backend, $frontend . '/') === 0) {
// backend use frontend htaccess
$this->backend_htaccess = $this->frontend_htaccess;
$this->backend_htaccess = $backend . '/.htaccess';
* Get corresponding htaccess path
* @param string $kind Frontend or backend
public function htaccess_path( $kind = 'frontend' ) {
$path = $this->backend_htaccess;
$path = $this->frontend_htaccess;
* Get the content of the rules file.
* NOTE: will throw error if failed
* @since 2.9 Used exception for failed reading
public function htaccess_read( $kind = 'frontend' ) {
$path = $this->htaccess_path($kind);
if (!$path || !file_exists($path)) {
if (!$this->_readable($kind)) {
$content = File::read($path);
if ($content === false) {
$content = str_ireplace("\x0D", '', $content);
* Try to backup the .htaccess file if we didn't save one before.
* NOTE: will throw error if failed
private function _htaccess_backup( $kind = 'frontend' ) {
$path = $this->htaccess_path($kind);
if (!file_exists($path)) {
if (file_exists($path . '.bk')) {
$res = copy($path, $path . '.bk');
// Failed to backup, abort
* Get mobile view rule from htaccess file
* NOTE: will throw error if failed
public function current_mobile_agents() {
$rules = $this->_get_rule_by(self::MARKER_MOBILE);
Error::t('HTA_DNF', self::MARKER_MOBILE);
// 'RewriteCond %{HTTP_USER_AGENT} ' . Utility::arr2regex( $cfg[ $id ], true ) . ' [NC]';
$match = substr($rule, strlen('RewriteCond %{HTTP_USER_AGENT} '), -strlen(' [NC]'));
Error::t('HTA_DNF', __('Mobile Agent Rules', 'litespeed-cache'));
* Parse rewrites rule from the .htaccess file.
* NOTE: will throw error if failed
public function current_login_cookie( $kind = 'frontend' ) {
$rule = $this->_get_rule_by(self::MARKER_LOGIN_COOKIE, $kind);
Error::t('HTA_DNF', self::MARKER_LOGIN_COOKIE);
if (strpos($rule, 'RewriteRule .? - [E=') !== 0) {
Error::t('HTA_LOGIN_COOKIE_INVALID');
$rule_cookie = substr($rule, strlen('RewriteRule .? - [E='), -1);
if (LITESPEED_SERVER_TYPE === 'LITESPEED_SERVER_OLS') {
$rule_cookie = trim($rule_cookie, '"');
$rule_cookie = substr($rule_cookie, strlen('Cache-Vary:'));
* Get rewrite rules based on the marker
private function _get_rule_by( $cond, $kind = 'frontend' ) {
$path = $this->htaccess_path($kind);
if (!$this->_readable($kind)) {
$rules = File::extract_from_markers($path, self::MARKER);
if (!in_array($cond . self::MARKER_START, $rules) || !in_array($cond . self::MARKER_END, $rules)) {
$key_start = array_search($cond . self::MARKER_START, $rules);
$key_end = array_search($cond . self::MARKER_END, $rules);
if ($key_start === false || $key_end === false) {
$results = array_slice($rules, $key_start + 1, $key_end - $key_start - 1);
if (count($results) == 1) {
return trim($results[0]);
return array_filter($results);
* Generate browser cache rules
* @return array Rules set
private function _browser_cache_rules( $cfg ) {
$id = Base::O_CACHE_TTL_BROWSER;
self::EXPIRES_MODULE_START,
// '<FilesMatch "\.(pdf|ico|svg|xml|jpg|jpeg|png|gif|webp|ogg|mp4|webm|js|css|woff|woff2|ttf|eot)(\.gz)?$">',
'ExpiresByType application/pdf A' . $ttl,
'ExpiresByType image/x-icon A' . $ttl,
'ExpiresByType image/vnd.microsoft.icon A' . $ttl,
'ExpiresByType image/svg+xml A' . $ttl,
'ExpiresByType image/jpg A' . $ttl,
'ExpiresByType image/jpeg A' . $ttl,
'ExpiresByType image/png A' . $ttl,
'ExpiresByType image/gif A' . $ttl,
'ExpiresByType image/webp A' . $ttl,
'ExpiresByType image/avif A' . $ttl,
'ExpiresByType video/ogg A' . $ttl,
'ExpiresByType audio/ogg A' . $ttl,
'ExpiresByType video/mp4 A' . $ttl,
'ExpiresByType video/webm A' . $ttl,
'ExpiresByType text/css A' . $ttl,
'ExpiresByType text/javascript A' . $ttl,
'ExpiresByType application/javascript A' . $ttl,
'ExpiresByType application/x-javascript A' . $ttl,
'ExpiresByType application/x-font-ttf A' . $ttl,
'ExpiresByType application/x-font-woff A' . $ttl,
'ExpiresByType application/font-woff A' . $ttl,
'ExpiresByType application/font-woff2 A' . $ttl,
'ExpiresByType application/vnd.ms-fontobject A' . $ttl,
'ExpiresByType font/ttf A' . $ttl,
'ExpiresByType font/otf A' . $ttl,
'ExpiresByType font/woff A' . $ttl,
'ExpiresByType font/woff2 A' . $ttl,
* Generate CORS rules for fonts
* @return array Rules set
private function _cors_rules() {
'<FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font\.css)$">',
'<IfModule mod_headers.c>',
'Header set Access-Control-Allow-Origin "*"',
* Generate rewrite rules based on settings
* @param array $cfg The settings to be used for rewrite rule
* @return array Rules array
private function _generate_rules( $cfg ) {
$new_rules_nonls = array();
$new_rules_backend = array();
$new_rules_backend_nonls = array();
// $id = Base::O_CRAWLER;
// if (!empty($cfg[$id])) {
$new_rules[] = self::MARKER_ASYNC . self::MARKER_START;
$new_rules[] = 'RewriteCond %{REQUEST_URI} /wp-admin/admin-ajax\.php';
$new_rules[] = 'RewriteCond %{QUERY_STRING} action=async_litespeed';
$new_rules[] = 'RewriteRule .* - [E=noabort:1]';
$new_rules[] = self::MARKER_ASYNC . self::MARKER_END;
$id = Base::O_CACHE_MOBILE_RULES;
if ((!empty($cfg[Base::O_CACHE_MOBILE]) || !empty($cfg[Base::O_GUEST])) && !empty($cfg[$id])) {
$new_rules[] = self::MARKER_MOBILE . self::MARKER_START;