如何使用名称中的空间以WebP格式提供图片?
我试图找到有关如何做我需要的事情的信息 - 但令我惊讶的是,什么也没有,所以我在这里写下来。
任务
将所有图像转换为 .webp 格式并用它们替换原始图像。
我做了什么
将所有图像转换为 .webp 并将它们放在原始图像附近:
- assets/img/img.png
- assets/img/img.webp
- ...
添加了 nginx 的规则。
# in http section
map $http_accept $webp_ext {
default "";
"~*webp" ".webp";
}
# in server section
location ~* ^(/.+)\.(png|jpe?g)$ {
set $img_path $1;
add_header Vary Accept;
try_files $img_path$webp_ext $uri =404;
}
它适用于名称中不带空格的图像,例如 img.png
,
但不适用于 img space.png
这样的图像
我如何提供它?
PS 我尝试过这在 Apache 上并且对于具有此 .htaccess
规则的两个图像,它的工作:
<IfModule mod_rewrite.c>
RewriteEngine On
# Check if browser supports WebP images
RewriteCond %{HTTP_ACCEPT} image/webp
# Check if WebP replacement image exists
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
# Serve WebP image instead
RewriteRule (.+)\.(jpe?g|png|gif)$ $1.webp [T=image/webp,E=REQUEST_image]
</IfModule>
<IfModule mod_headers.c>
# Vary: Accept for all the requests to jpeg, png and gif
Header append Vary Accept env=REQUEST_image
</IfModule>
<IfModule mod_mime.c>
AddType image/webp .webp
</IfModule>
I tried to find information on how to do what I need - but to my surprise there was nothing at all, so I'm writing here.
TASK
Convert all images to .webp format and replace original images by them.
WHAT I DID
Converted all the images to .webp and put them near to the original images:
- assets/img/img.png
- assets/img/img.webp
- ...
Added rules for nginx.
# in http section
map $http_accept $webp_ext {
default "";
"~*webp" ".webp";
}
# in server section
location ~* ^(/.+)\.(png|jpe?g)$ {
set $img_path $1;
add_header Vary Accept;
try_files $img_path$webp_ext $uri =404;
}
Its works for images that are named without space in name like img.png
But dont work for images like img space.png
How it looks in the Network panel
How i can serve it?
P.S. I tried do this on Apache
and its work for both images with this .htaccess
rules:
<IfModule mod_rewrite.c>
RewriteEngine On
# Check if browser supports WebP images
RewriteCond %{HTTP_ACCEPT} image/webp
# Check if WebP replacement image exists
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
# Serve WebP image instead
RewriteRule (.+)\.(jpe?g|png|gif)$ $1.webp [T=image/webp,E=REQUEST_image]
</IfModule>
<IfModule mod_headers.c>
# Vary: Accept for all the requests to jpeg, png and gif
Header append Vary Accept env=REQUEST_image
</IfModule>
<IfModule mod_mime.c>
AddType image/webp .webp
</IfModule>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$ uri具有20%解码,而$ img_path则没有。
重写应该在这里有所帮助:
随着更改以说明“ http_accept”
$uri has %20 decoded while $img_path is not.
rewrite should help here:
with the changes to account for 'http_accept' of course