htaccess服务器端WEBP检测与WordPress htaccess规则结合使用

pat*_*zdb 1 apache wordpress .htaccess mod-rewrite webp

我有我的htaccess文件设置如下:

<IfModule mod_rewrite.c>
  RewriteEngine On
  # check if browser accepts webp
  RewriteCond %{HTTP_ACCEPT} image/webp 

  # check if file is jpg or png
  RewriteCond %{REQUEST_FILENAME} (.*)\.(jpe?g|png)$

  # check if corresponding webp file exists image.png -> image.webp
  RewriteCond %1\.webp -f

  # serve up webp instead
  RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]

</IfModule>

<IfModule mod_headers.c>
  Header append Vary Accept env=REDIRECT_accept
</IfModule>

AddType image/webp .webp
Run Code Online (Sandbox Code Playgroud)

它在测试目录中运行良好,并显示一个webp图像(如果存在).但是,当我尝试将相同的.htaccess规则与WordPress的相当永久链接重写规则结合使用时,规则就会中断.

这是WordPress的默认规则(如果您的子目录称为DPA)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /DPA/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /DPA/index.php [L]
</IfModule>
Run Code Online (Sandbox Code Playgroud)

如果我尝试直接访问jpg文件,我在服务器上收到以下错误:

The requested URL /wp-content/themes/dpa/assets/img/home-page/sliders/strategy-1650.webp was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Run Code Online (Sandbox Code Playgroud)

我想这是因为WordPress在根目录中查找文件并弄乱了图像文件的实际位置.

有没有人知道重写规则在apache上使两个规则相互兼容?

谢谢!

帕特里克

pat*_*zdb 6

这对我有用,

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /DPA/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /DPA/index.php [L]
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /DPA/
  # check if browser accepts webp
  RewriteCond %{HTTP_ACCEPT} image/webp 

  # check if file is jpg or png
  RewriteCond %{REQUEST_FILENAME} (.*)\.(jpe?g|png)$

  # check if corresponding webp file exists image.png -> image.webp
  RewriteCond %1\.webp -f

  # serve up webp instead
  RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]

</IfModule>

<IfModule mod_headers.c>
  Header append Vary Accept env=REDIRECT_accept
</IfModule>

AddType image/webp .webp
Run Code Online (Sandbox Code Playgroud)

我添加了RewriteBase/DPA /到webp检查,现在它工作正常.

我刚刚意识到我包含了默认的WordPress相当永久链接代码,但它应该是目录的一个.我现在要编辑这个问题.