如何通过GET请求将所有PNG,JPG和JPEG链接重定向到特定的PHP文件

时间:2019-05-17 17:29:41

标签: php wordpress .htaccess webp

我正在开发可优化网站的WordPress插件。当前,我正在尝试使用Rosell-dk的webp库https://github.com/rosell-dk/webp-on-demand将所有图像(PNG,JPG和JPEG)图像转换为Webp,该库支持通过.htaccess作为GET请求发送图像链接。但不幸的是,它不起作用,我不确定自己做错了还是我的方法完全错误。

我尝试编写Rosell-dk在GitHub页面https://github.com/rosell-dk/webp-on-demand上声明的规则,但不幸的是,它们不起作用。以下是我在WordPress安装的“ wp-content”文件夹中创建的.htaccess文件上粘贴的规则,因为WordPress网站的所有图像都驻留在其中。

<IfModule mod_rewrite.c>
RewriteEngine On

# Redirect images to webp-on-demand.php (if browser supports webp)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteRule ^(.*)\.(jpe?g|png)$ /plugins/*my plugin name*/inc/webp-converter/webp-on-demand.php?source=%{SCRIPT_FILENAME} [NC,L]
</IfModule>

在我的“ webp-on-demand.php”中,我有以下内容

$imageSource  = $_GET['source'];

不幸的是,文件“ webp-on-demand.php”根本没有被调用。

如果你们能帮助我找出正确的规则或哪里出了问题,那将是很棒的事情。

1 个答案:

答案 0 :(得分:0)

如前所述,您正在使用nginx,以下步骤应会为您提供帮助。

首先,检查mime类型是否具有webp

cat /etc/nginx/mime.types | grep webp

它应该告诉你

image/webp  webp;

现在

server{
  location ~* ^(/wp-content/.+)\.(png|jpe?g)$ {
    set $base $1;
    set $webp_uri $base$webp_suffix;
    set $webp_old_uri $base.$2$webp_suffix;
    set $root "<<FULL PATH OF wp-content PARENT>>";
    root $root;
    add_header Vary Accept;
    if ( !-f $root$webp_uri ) {
        rewrite ^(.*)\.(jpe?g|png)$ /wp-content/plugins/*your plugin name*/inc/webp-converter/webp-on-demand.php?source=$webp_uri break;
    }
    try_files $webp_uri $webp_old_uri $uri =404;
  }
}

确保将<<FULL PATH OF wp-content PARENT>>替换为实际的磁盘路径