Tối ưu hình ảnh WordPress qua file server

Tối ưu hình ảnh WordPress qua file server

|28/5/2025|꧁༺Quốc༒Hùng༻꧂

Bước 1. Thêm code cho web server hứng request file .jpg | .png

Để xác định khách đang xem / tải ảnh nào thì chỉ có thể xử lý ở tầng Web Server. Ta cần thêm cấu hình rewrite trong .htaccess hoặc nginx.conf để hứng các request có đuôi là .webp hoặc .jpg.webp, .png.webp…

Nếu thư mục đã có ảnh .webp thì lấy trực tiếp nó ra. Nếu chưa có thì lấy data của ảnh .jpg hoặc .png để hiển thị thông qua link .jpg .webp.

Trường hợp 1: Thêm code vào đầu file .htaccess (Nếu bạn sử dụng máy chủ Apache hoặc Litespeed)


#Thêm đoạn này vào vị trí đầu file .htaccess của bạn
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_URI} (.+)\.(jpeg|png|jpg)$
RewriteCond %{DOCUMENT_ROOT}/$1\.webp -f
RewriteRule (.+)\.(jpeg|png|jpg)$ %{REQUEST_URI}.webp [QSA,L]
#DONE LOAD FILE WEBP VÀO FILE ẢNH THƯỜNGRewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_URI} (.+)\.(jpeg|png|jpg)$
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} -f
RewriteCond %{DOCUMENT_ROOT}/$1\.webp !-f
RewriteRule (.+)\.(jpeg|png|jpg)$ /image2webp.php?source=%{DOCUMENT_ROOT}/$1.$2 [QSA,L]
#DONE TỰ TẠO FILE WEBP NẾU CHƯA CÓRewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_URI} (.+)\.webp$
RewriteCond %{DOCUMENT_ROOT}/$1 -f
RewriteCond %{DOCUMENT_ROOT}/$1\.webp !-f
RewriteRule (.+)\.webp$ /image2webp.php?source=%{DOCUMENT_ROOT}/$1 [QSA,L]
#TẠO FILE WEBP KHI TRUY CẬP VÀ THƯỜNG
</IfModule>

Trường hợp 2: Thêm code vào đầu file nginx.conf (Đối với máy chủ Nginx)

#Thêm đoạn này vào vị trí đầu file nginx.conf của bạn
location ~* ^/(.*)\.webp$ {
access_log off;
log_not_found off;
expires 365d;
location ~* ^/(.*)\.(.*)\.webp$ {
set $original_file $1;
set $extension $2;
if (-f $document_root/$original_file.$extension.webp) {
break;
}
set $is_file "no";
if (-f $document_root/$original_file.$extension) {
set $is_file "yes";
}
if (-f $document_root/image2webp.php) {
set $is_file "${is_file}yes";
}
if ($is_file = "yesyes") {
rewrite ^(.*)$ /image2webp.php?source=$document_root/$original_file.$extension last;
}
if ($is_file = "yes") {
rewrite ^(.*)$ /$original_file.$extension last;
}
return 404;
}
set $original_file $1;
if (-f $document_root/$original_file.webp) {
break;
}
if (-f $document_root/$original_file.png) {
rewrite ^(.*)$ /$original_file.png last;
}
if (-f $document_root/$original_file.jpg) {
rewrite ^(.*)$ /$original_file.jpg last;
}
if (-f $document_root/$original_file.gif) {
rewrite ^(.*)$ /$original_file.gif last;
}
return 404;
}location ~* ^/(.*)\.(jpeg|png|jpg)$ {
access_log off;
log_not_found off;
expires 365d;
set $webp_rewrite "yes";
if ($http_accept !~ "image/webp") {
set $webp_rewrite "no";
}
if (-f $document_root$uri.webp) {
set $webp_rewrite "${webp_rewrite}yes";
}
if ($webp_rewrite = "yesyes") {
rewrite ^(.*)$ $1.webp last;
}
if (-f $document_root/image2webp.php) {
set $webp_rewrite "${webp_rewrite}yes";
}
if ($webp_rewrite = "yesyes") {
rewrite ^(.*)$ /image2webp.php?source=$document_root$uri last;
}
try_files $uri $uri/ =404;}

Bước 2. Tạo file PHP để convert ảnh sang định dạng .webp

Bạn tạo file image2webp.php ở thư mục gốc của website (ngang hàng với file wp-config.php) và thêm code bên dưới vào file vừa tạo. File này dùng để nhận yêu cầu nén và tạo file ảnh webp từ Web Server nếu chưa có.

<?php
if (isset($_GET['source'])) {
$source = $_GET['source'];
if ((strpos($source, '/wp-content/themes') == true) || (strpos($source, '/wp-content/plugins') == true) || (strpos($source, '/wp-content/uploads') == true)) {
if (file_exists($source.'.webp')) {
if (filesize($source.'.webp') ==0) {
generate_webp($source,90);
}
get_webp_file($source);
}
else {
if (file_exists($source)) {
if (generate_webp($source,80)) {
get_webp_file($source);
} else {
header($_SERVER["SERVER_PROTOCOL"] . "404 Not Found");
}
} else {
header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
}
}
} else {header($_SERVER["SERVER_PROTOCOL"] . " 403 Forbidden");
}
}
function get_webp_file($source){
$path_to_webp = $source.'.webp';
$file_get = file_get_contents($path_to_webp);
$file_out = $path_to_webp;
file_put_contents($file_out,$file_get);
if (file_exists($file_out)) {
$image_info = getimagesize($file_out);
header('Content-Type: image/webp');
header('Content-Length: ' . filesize($file_out));
header('Cache-Control: max-age=31536000');
readfile($file_out);
}
}
function generate_webp($file,$compression_quality){ //Hàm tạo ảnh .webp
$output_file = $file . '.webp';
if (file_exists($output_file) && (filesize($output_file) !==0)) {
return true;
}
$file_type = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (function_exists('imagewebp')) {
switch ($file_type) {
case 'jpeg':
case 'jpg':
$image = @ImageCreateFromJpeg($file);
if (!$image){$image= imagecreatefromstring(file_get_contents($file));}
break;
case 'png':
$image = imagecreatefrompng($file);
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
break;
default:
return false;
}
$result = imagewebp($image, $output_file, $compression_quality);
if (false === $result) {
// Free up memory
imagedestroy($image);
return false;
} else {
// Free up memory
imagedestroy($image);
return true;
}
}
}
?>
Chia sẻ:

Tin liên quan khác

Tăng Số Luồng Xử Lý PHP: Toàn Tập Tối Ưu Hiệu Năng Server
Lập Trình
5/10/2025
꧁༺Quốc༒Hùng༻꧂

Tăng Số Luồng Xử Lý PHP: Toàn Tập Tối Ưu Hiệu Năng Server

Trong ngữ cảnh phổ biến nhất hiện nay với PHP-FPM (FastCGI Process Manager), “luồng xử lý” thực chất là các tiến trình con (child processes) hay còn gọi là worker processes

Tạo Index trong SQL: Review Chi Tiết và Ví Dụ Thực Tế
Lập Trình
17/8/2025
꧁༺Quốc༒Hùng༻꧂

Tạo Index trong SQL: Review Chi Tiết và Ví Dụ Thực Tế

Index là gì, các loại phổ biến, ưu nhược điểm thực tế, so sánh khi nào nên dùng loại nào

7+ CLI Đọc & Phân Tích Ổ Cứng Linux Hiệu Quả Cho Sysadmin
DevOps
17/8/2025
꧁༺Quốc༒Hùng༻꧂

7+ CLI Đọc & Phân Tích Ổ Cứng Linux Hiệu Quả Cho Sysadmin

(CLI) không chỉ là một công cụ mà còn là một nghệ thuật. Đối với việc quản lý và chẩn đoán ổ cứng, CLI tỏ ra vượt trội hơn hẳn các công cụ đồ họa

Index trong SQL: Bí kíp tăng tốc truy vấn dữ liệu hiệu quả
Lập Trình
16/8/2025
꧁༺Quốc༒Hùng༻꧂

Index trong SQL: Bí kíp tăng tốc truy vấn dữ liệu hiệu quả

Hãy tưởng tượng Index trong sql giống hệt như mục lục ở cuối một cuốn sách dày

Chuyển Hướng Website: Bí Quyết SEO & Trải Nghiệm Người Dùng Hoàn Hảo
SEO
30/5/2025
꧁༺Quốc༒Hùng༻꧂

Chuyển Hướng Website: Bí Quyết SEO & Trải Nghiệm Người Dùng Hoàn Hảo

Một trong những kỹ thuật quan trọng nhất để đảm bảo sự ổn định, cải thiện SEO và mang lại trải nghiệm người dùng tốt nhất chính là chuyển hướng website (redirect)

Sitemap Website: Bí Mật SEO Hiệu Quả
Lập Trình
30/5/2025
꧁༺Quốc༒Hùng༻꧂

Sitemap Website: Bí Mật SEO Hiệu Quả

Sitemap Website (hay bản đồ trang web) là một tệp văn bản chứa danh sách tất cả các trang quan trọng trên website của bạn

Cách Cấu Hình và Cài Đặt Cơ Bản Khi Clone Source Laravel Từ GitHub
Laravel
25/5/2025
꧁༺Quốc༒Hùng༻꧂

Cách Cấu Hình và Cài Đặt Cơ Bản Khi Clone Source Laravel Từ GitHub

Việc clone source code từ GitHub là bước đầu tiên để bắt đầu một dự án Laravel mới hoặc đóng góp vào một dự án hiện có