Thủ thuật tối ưu LAMP server qua htaccess


Tận dụng browser caching

Mình sẽ hướng dẫn các bạn cách thêm Expires headers vào file .htaccess để tận dụng browser caching. Phương pháp này giúp giảm thiểu tối đa HTTP request đến server bằng cách sử dụng những file tĩnh như hình ảnh, css, javascript đã lưu trong cache của browser lúc bạn truy cập website lần đầu tiên.

Cách thêm Expires header

Trong ví dụ này mình sẽ thêm header cho một số loại file tĩnh như:

Thời gian lưu cache thì bạn có thể tùy chọn

Đây là đoạn code mình sử dụng, các bạn thêm vào cuối file .htaccess

<IfModule mod_expires.c>

# Enable expirations
ExpiresActive On

# Default directive
ExpiresDefault "access plus 1 month"

# My favicon
ExpiresByType image/x-icon "access plus 1 year"

# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"

# CSS
ExpiresByType text/css "access 1 month"

# Javascript
ExpiresByType application/javascript "access plus 1 year"

</IfModule>

Kích hoạt GZIP Compression cho Apache Server

GZIP giúp tối ưu và tăng tốc website bằng cách nén nội dung trả về từ server mỗi khi có request gửi đến.

Để thực hiện, các bạn chỉ cần thêm đoạn sau vào cuối file .htaccess. Apache 1.3 sử dụng mod_gzip trong khi Apache 2.x sử dụng mod_deflate.

Để kiểm tra Apache Version các bạn sử dụng lệnh:

httpd -v

Cấu hình mod_gzip cho Apache 1.3.x

<IfModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|txt|css|js|php)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

Cấu hình mod_deflate cho Apache 2.x

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
# Don't compress
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
#Dealing with proxy servers
<IfModule mod_headers.c>
Header append Vary User-Agent
</IfModule>
</IfModule>

Để test lại xem đã thành công hay chưa các bạn sử dụng tool http://redbot.org, điền link site bạn vào và tìm xem có dòng Content-Encoding: gzip trong kết quả trả về là được.



Article ID: 16
Created On: Fri, Feb 26, 2016 at 10:48 PM
Last Updated On: Fri, Feb 26, 2016 at 11:33 PM
Authored by: Đặng Văn Kiên [info@vinastar.net]

Online URL: https://doc.vinastar.net/article.php?id=16