* @param string|false $postfix File extension (with dot) when mapping by file type.
* @return string|false Replaced URL on success, false when not applicable.
public function rewrite( $url, $mapping_kind, $postfix = false ) {
self::debug2( 'rewrite ' . $url );
$url_parsed = wp_parse_url( $url );
if ( empty( $url_parsed['path'] ) ) {
self::debug2( '-rewrite bypassed: no path' );
// Only images under wp-content/wp-includes can be replaced
$is_internal_folder = Utility::str_hit_array( $url_parsed['path'], $this->_cfg_ori_dir );
if ( ! $is_internal_folder ) {
self::debug2( '-rewrite failed: path not match: ' . LSCWP_CONTENT_FOLDER );
// Check if is external url
if ( ! empty( $url_parsed['host'] ) ) {
if ( ! Utility::internal( $url_parsed['host'] ) && ! $this->_is_ori_url( $url ) ) {
self::debug2( '-rewrite failed: host not internal' );
$exclude = Utility::str_hit_array( $url, $this->_cfg_cdn_exclude );
self::debug2( '-abort excludes ' . $exclude );
// Fill full url before replacement
if ( empty( $url_parsed['host'] ) ) {
$url = Utility::uri2url( $url );
self::debug2( '-fill before rewritten: ' . $url );
$url_parsed = wp_parse_url( $url );
$scheme = ! empty( $url_parsed['scheme'] ) ? $url_parsed['scheme'] . ':' : '';
// Find the mapping url to be replaced to
if ( empty( $this->_cfg_cdn_mapping[ $mapping_kind ] ) ) {
if ( Base::CDN_MAPPING_FILETYPE !== $mapping_kind ) {
$final_url = $this->_cfg_cdn_mapping[ $mapping_kind ];
$final_url = $this->_cfg_cdn_mapping[ $postfix ];
// If filetype to url is one to many, need to random one
if ( is_array( $final_url ) ) {
$final_url = $final_url[ array_rand( $final_url ) ];
// Now lets replace CDN url
foreach ( $this->_cfg_url_ori as $v ) {
if ( false !== strpos( $v, '*' ) ) {
$url = preg_replace( '#' . $scheme . $v . '#iU', $final_url, $url );
$url = str_replace( $scheme . $v, $final_url, $url );
self::debug2( '-rewritten: ' . $url );
* Check if the given URL matches any configured "original" URLs for CDN.
* @param string $url URL to test.
* @return bool True if URL is one of the originals.
private function _is_ori_url( $url ) {
$url_parsed = wp_parse_url( $url );
$scheme = ! empty( $url_parsed['scheme'] ) ? $url_parsed['scheme'] . ':' : '';
foreach ( $this->_cfg_url_ori as $v ) {
if ( false !== strpos( $v, '*' ) ) {
if ( preg_match( '#' . $needle . '#iU', $url ) ) {
} elseif ( 0 === strpos( $url, $needle ) ) {
* Check if the host is one of the CDN mapping hosts.
* @param string $host Hostname to check.
* @return bool False when bypassed, otherwise true if internal CDN host.
public static function internal( $host ) {
if ( defined( self::BYPASS ) ) {
return in_array( $host, $instance->cdn_mapping_hosts, true ); // todo: can add $this->_is_ori_url() check in future