| 1 |
<?php |
| 2 |
namespace Imagify\Webp\RewriteRules; |
| 3 |
|
| 4 |
defined( 'ABSPATH' ) || die( 'Cheatin’ uh?' ); |
| 5 |
|
| 6 |
/** |
| 7 |
* Add and remove rewrite rules to the .htaccess file to display webp images on the site. |
| 8 |
* |
| 9 |
* @since 1.9 |
| 10 |
* @author Grégory Viguier |
| 11 |
*/ |
| 12 |
class Apache extends \Imagify\WriteFile\AbstractApacheDirConfFile { |
| 13 |
|
| 14 |
/** |
| 15 |
* Name of the tag used as block delemiter. |
| 16 |
* |
| 17 |
* @var string |
| 18 |
* @since 1.9 |
| 19 |
* @author Grégory Viguier |
| 20 |
*/ |
| 21 |
const TAG_NAME = 'Imagify: rewrite rules for webp'; |
| 22 |
|
| 23 |
/** |
| 24 |
* Get unfiltered new contents to write into the file. |
| 25 |
* |
| 26 |
* @since 1.9 |
| 27 |
* @access protected |
| 28 |
* @source https://github.com/vincentorback/WebP-images-with-htaccess |
| 29 |
* @author Grégory Viguier |
| 30 |
* |
| 31 |
* @return string |
| 32 |
*/ |
| 33 |
protected function get_raw_new_contents() { |
| 34 |
$extensions = $this->get_extensions_pattern(); |
| 35 |
$home_root = wp_parse_url( home_url( '/' ) ); |
| 36 |
$home_root = $home_root['path']; |
| 37 |
|
| 38 |
return trim( ' |
| 39 |
<IfModule mod_setenvif.c> |
| 40 |
# Vary: Accept for all the requests to jpeg, png, and gif. |
| 41 |
SetEnvIf Request_URI "\.(' . $extensions . ')$" REQUEST_image |
| 42 |
</IfModule> |
| 43 |
|
| 44 |
<IfModule mod_rewrite.c> |
| 45 |
RewriteEngine On |
| 46 |
RewriteBase ' . $home_root . ' |
| 47 |
|
| 48 |
# Check if browser supports WebP images. |
| 49 |
RewriteCond %{HTTP_ACCEPT} image/webp |
| 50 |
|
| 51 |
# Check if WebP replacement image exists. |
| 52 |
RewriteCond %{REQUEST_FILENAME}.webp -f |
| 53 |
|
| 54 |
# Serve WebP image instead. |
| 55 |
RewriteRule (.+)\.(' . $extensions . ')$ $1.$2.webp [T=image/webp,NC] |
| 56 |
</IfModule> |
| 57 |
|
| 58 |
<IfModule mod_headers.c> |
| 59 |
Header append Vary Accept env=REQUEST_image |
| 60 |
</IfModule>' ); |
| 61 |
} |
| 62 |
} |
| 63 |
|