1. OPcache Là Gì?
OPcache là một extension của PHP giúp tối ưu hóa hiệu suất bằng cách lưu trữ các bytecode đã được biên dịch của các file PHP vào bộ nhớ. Điều này giúp giảm thời gian tải và thực thi mã PHP, đặc biệt quan trọng đối với các website có lượng truy cập lớn.

Khi OPcache được bật, thay vì phải biên dịch lại mã PHP mỗi lần có request, server sẽ sử dụng phiên bản đã được lưu trong cache, giúp giảm tải CPU và tăng tốc xử lý.
2. Cài Đặt OPcache.
Trên Ubuntu/Debian:
sudo apt update
sudo apt install php-opcache -y
Trên CentOS/RHEL:
sudo yum install php-opcache -y
Sau khi cài đặt, kiểm tra lại xem OPcache đã có trong danh sách module chưa. Lệnh php -i | grep opcache
sẽ kiểm tra xem OPcache đã được bật chưa. Nếu không thấy kết quả nào, bạn cần kiểm tra lại cấu hình trong file php.ini
.
php -i | grep opcache
Nếu OPcache chưa được bật, bạn có thể mở file config PHP để kích hoạt ở bước tiếp theo.
3. Cấu Hình OPcache
Sau khi cài đặt, bạn cần cấu hình OPcache để tối ưu hóa hiệu suất.
Mở file config OPcache /etc/php/8.1/fpm/conf.d/10-opcache.ini,
/etc/php/8.1/cli/php.ini
hoặc /etc/php/8.1/fpm/php.ini
nhưng ưu tiên chỉnh trong /etc/php/8.1/fpm/conf.d/10-opcache.ini
.
Lý do:
/etc/php/8.1/fpm/conf.d/10-opcache.ini
chứa các cài đặt riêng cho OPcache./etc/php/8.1/fpm/php.ini
và/etc/php/8.1/cli/php.ini
là file config chung của PHP-FPM, nên chỉnh trong đây cũng được, nhưng không khuyến khích vì có thể ảnh hưởng đến các thiết lập khác.
Cách chỉnh OPcache cho PHP-FPM
Mở file 10-opcache.ini
:
vi /etc/php/8.1/fpm/conf.d/10-opcache.ini
Thêm hoặc chỉnh sửa các dòng sau:
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.validate_timestamps=1
opcache.revalidate_freq=60
opcache.jit=tracing
opcache.jit_buffer_size=64M
(Nếu bạn dùng phiên bản PHP khác, thay 8.1
bằng phiên bản phù hợp.)
Lưu ý:
opcache.enable=1
: Bật OPcache.opcache.memory_consumption=
: Cấp phát 256MB RAM cho OPcache, giúp tăng bộ nhớ cache nếu server có RAM dư dả.256
opcache.max_accelerated_files=20000
: Lưu trữ tối đa 20,000 file đã biên dịch.opcache.validate_timestamps=1
: Kiểm tra lại các file PHP khi có thay đổi.opcache.revalidate_freq=60
: Kiểm tra thay đổi sau mỗi 60 giây.opcache.interned_strings_buffer=16
: Bộ nhớ dành riêng cho chuỗi nội bộ.opcache.fast_shutdown=1
: Tắt nhanh để tối ưu hiệu suất.opcache.enable_cli=0
: để tránh ảnh hưởng đến CLI (vì CLI không cần OPcache).
Sau khi chỉnh sửa xong, bạn cần khởi động lại PHP-FPM và Nginx:
sudo systemctl restart php8.1-fpm
sudo systemctl restart nginx
Sau đó, kiểm tra lại với lệnh php -i | grep opcache
xem OPcache đã được bật chưa. Nếu vẫn chưa thấy, bạn có thể chạy lệnh php -v
để kiểm tra lỗi trong cấu hình:
shell> php -i | grep opcache
/etc/php/8.1/cli/conf.d/10-opcache.ini,
opcache.blacklist_filename => no value => no value
opcache.consistency_checks => 0 => 0
opcache.dups_fix => Off => Off
opcache.enable => On => On
opcache.enable_cli => On => On
opcache.enable_file_override => Off => Off
opcache.error_log => no value => no value
opcache.file_cache => no value => no value
opcache.file_cache_consistency_checks => On => On
opcache.file_cache_only => Off => Off
opcache.file_update_protection => 2 => 2
opcache.force_restart_timeout => 180 => 180
opcache.huge_code_pages => Off => Off
opcache.interned_strings_buffer => 16 => 16
opcache.jit => tracing => tracing
opcache.jit_bisect_limit => 0 => 0
opcache.jit_blacklist_root_trace => 16 => 16
opcache.jit_blacklist_side_trace => 8 => 8
opcache.jit_buffer_size => 64M => 64M
opcache.jit_debug => 0 => 0
opcache.jit_hot_func => 127 => 127
opcache.jit_hot_loop => 64 => 64
opcache.jit_hot_return => 8 => 8
opcache.jit_hot_side_exit => 8 => 8
opcache.jit_max_exit_counters => 8192 => 8192
opcache.jit_max_loop_unrolls => 8 => 8
opcache.jit_max_polymorphic_calls => 2 => 2
opcache.jit_max_recursive_calls => 2 => 2
opcache.jit_max_recursive_returns => 2 => 2
opcache.jit_max_root_traces => 1024 => 1024
opcache.jit_max_side_traces => 128 => 128
opcache.jit_prof_threshold => 0.005 => 0.005
opcache.lockfile_path => /tmp => /tmp
opcache.log_verbosity_level => 1 => 1
opcache.max_accelerated_files => 20000 => 20000
opcache.max_file_size => 0 => 0
opcache.max_wasted_percentage => 5 => 5
opcache.memory_consumption => 256 => 256
opcache.opt_debug_level => 0 => 0
opcache.optimization_level => 0x7FFEBFFF => 0x7FFEBFFF
opcache.preferred_memory_model => no value => no value
opcache.preload => no value => no value
opcache.preload_user => no value => no value
opcache.protect_memory => Off => Off
opcache.record_warnings => Off => Off
opcache.restrict_api => no value => no value
opcache.revalidate_freq => 60 => 60
opcache.revalidate_path => Off => Off
opcache.save_comments => On => On
opcache.use_cwd => On => On
opcache.validate_permission => Off => Off
opcache.validate_root => Off => Off
opcache.validate_timestamps => On => On
Nếu có lỗi, bạn dùng lệnh php -v
để xem log lỗi nếu có.
shell> php -v
PHP 8.1.2-1ubuntu2.20 (cli) (built: Dec 3 2024 20:14:35) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
with Zend OPcache v8.1.2-1ubuntu2.20, Copyright (c), by Zend Technologies
Để kiểm tra xem OPcache đã hoạt động chưa, tạo một file PHP trong thư mục /var/www/wiki.hoanghd.com
:
echo "<?php phpinfo(); ?>" | sudo tee /var/www/wiki.hoanghd.com/info.php
Rồi truy cập: https://wiki.hoanghd.com/info.php
và tìm phần Zend OPcache, nếu có, nghĩa là OPcache đã được kích hoạt.

Kiểm tra trạng thái OPcache qua API.
Bạn có thể chạy đoạn code sau để kiểm tra chi tiết OPcache, tạo file /var/www/wiki.hoanghd.com/opcache_status.php.
<?php print_r(opcache_get_status()); ?>
Truy cập trình duyệt nếu thấy các thông tin như "opcache_enabled" => true
, "cache_full" => false
, có nghĩa là OPcache đã chạy.

- Dựa vào output này, Zend OPcache đã được kích hoạt và đang hoạt động:
opcache_enabled => 1
→ OPcache đã được bật. ✅cache_full
không có giá trị → OPcache vẫn còn bộ nhớ trống, chưa bị đầy. ✅used_memory
vàfree_memory
có giá trị → OPcache đang cache các script PHP. ✅num_cached_scripts => 436
→ Có 436 script PHP đã được cache. ✅
Lưu ý:
- Nếu bạn chỉ chạy PHP qua web server (FPM), thì OPcache vẫn đang hoạt động bình thường, không có vấn đề gì.
- Nếu bạn muốn bật OPcache cho PHP CLI, hãy kiểm tra và bật
opcache.enable_cli
.
5. Cấu Hình OPcache Trong Nginx
Trong file config Nginx /etc/nginx/conf.d/wiki.hoanghd.com.conf
, bạn có thể bật OPcache với cache FastCGI:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# Bật FastCGI Cache
fastcgi_cache PHP_CACHE;
fastcgi_cache_valid 200 301 30m;
fastcgi_cache_use_stale updating error timeout invalid_header http_500;
fastcgi_cache_lock on;
fastcgi_cache_min_uses 2;
fastcgi_cache_methods GET HEAD;
}
Cấu hình đẩy đủ.
cat > /etc/nginx/conf.d/wiki.hoanghd.com.conf << 'OEF'
server {
listen 80;
server_name wiki.hoanghd.com;
# Redirect HTTP to HTTPS
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name wiki.hoanghd.com;
ssl_certificate /etc/nginx/ssl/wiki.hoanghd.com.pem;
ssl_certificate_key /etc/nginx/ssl/wiki.hoanghd.com.pem;
ssl_trusted_certificate /etc/nginx/ssl/wiki.hoanghd.com.pem;
root /var/www/wiki.hoanghd.com;
index index.php index.html index.htm;
# Ghi log truy cập và lỗi
access_log /var/log/nginx/wiki_access.log combined;
error_log /var/log/nginx/wiki_error.log warn;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
location / {
try_files $uri $uri/ /index.php?$args;
}
# Cấu hình xử lý PHP-FPM
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# Bật FastCGI Cache
fastcgi_cache PHP_CACHE;
fastcgi_cache_valid 200 301 30m;
fastcgi_cache_use_stale updating error timeout invalid_header http_500;
fastcgi_cache_lock on;
fastcgi_cache_min_uses 2;
fastcgi_cache_methods GET HEAD;
# Bỏ qua cache nếu có Set-Cookie hoặc nếu user đăng nhập
fastcgi_cache_bypass $http_cookie;
fastcgi_no_cache $http_cookie;
# Debug trạng thái cache
add_header X-FastCGI-Cache $upstream_cache_status;
}
# Caching file tĩnh (CSS, JS, ảnh, fonts)
location ~* \.(?:css|js|gif|jpe?g|png|ico|woff2?|ttf|svg|eot|mp4|webm|ogg|ogv|zip|pdf)$ {
expires 365d;
add_header Cache-Control "public, max-age=31536000, immutable";
}
# Chặn truy cập file ẩn
location ~ /\. {
deny all;
}
# Trang lỗi tùy chỉnh
error_page 403 /error403.html;
location = /error403.html {
internal;
root /var/www/wiki.hoanghd.com;
}
}
OEF
7. Kiểm Tra Trạng Thái OPcache
Bạn có thể kiểm tra số file được cache bằng lệnh:
php -r 'print_r(opcache_get_configuration());'
Từ ví dụ output dưới của opcache_get_configuration()
, ta có thể thấy rằng OPcache đã được bật.
shell> php -r 'print_r(opcache_get_configuration());'
Array
(
[directives] => Array
(
[opcache.enable] => 1
[opcache.enable_cli] => 1
[opcache.use_cwd] => 1
[opcache.validate_timestamps] => 1
[opcache.validate_permission] =>
[opcache.validate_root] =>
[opcache.dups_fix] =>
[opcache.revalidate_path] =>
[opcache.log_verbosity_level] => 1
[opcache.memory_consumption] => 268435456
[opcache.interned_strings_buffer] => 16
[opcache.max_accelerated_files] => 20000
[opcache.max_wasted_percentage] => 0.05
[opcache.consistency_checks] => 0
[opcache.force_restart_timeout] => 180
[opcache.revalidate_freq] => 60
[opcache.preferred_memory_model] =>
[opcache.blacklist_filename] =>
[opcache.max_file_size] => 0
[opcache.error_log] =>
[opcache.protect_memory] =>
[opcache.save_comments] => 1
[opcache.record_warnings] =>
[opcache.enable_file_override] =>
[opcache.optimization_level] => 2147401727
[opcache.lockfile_path] => /tmp
[opcache.file_cache] =>
[opcache.file_cache_only] =>
[opcache.file_cache_consistency_checks] => 1
[opcache.file_update_protection] => 2
[opcache.opt_debug_level] => 0
[opcache.restrict_api] =>
[opcache.huge_code_pages] =>
[opcache.preload] =>
[opcache.preload_user] =>
[opcache.jit] => tracing
[opcache.jit_buffer_size] => 67108864
[opcache.jit_debug] => 0
[opcache.jit_bisect_limit] => 0
[opcache.jit_blacklist_root_trace] => 16
[opcache.jit_blacklist_side_trace] => 8
[opcache.jit_hot_func] => 127
[opcache.jit_hot_loop] => 64
[opcache.jit_hot_return] => 8
[opcache.jit_hot_side_exit] => 8
[opcache.jit_max_exit_counters] => 8192
[opcache.jit_max_loop_unrolls] => 8
[opcache.jit_max_polymorphic_calls] => 2
[opcache.jit_max_recursive_calls] => 2
[opcache.jit_max_recursive_returns] => 2
[opcache.jit_max_root_traces] => 1024
[opcache.jit_max_side_traces] => 128
[opcache.jit_prof_threshold] => 0
)
[version] => Array
(
[version] => 8.1.2-1ubuntu2.20
[opcache_product_name] => Zend OPcache
)
[blacklist] => Array
(
)
)
Nhưng để kiểm tra xem nó đã thực sự cache script PHP chưa, bạn cần kiểm tra trạng thái bằng lệnh:
shell> php -r 'print_r(opcache_get_status());'
Array
(
[opcache_enabled] => 1
[cache_full] =>
[restart_pending] =>
[restart_in_progress] =>
[memory_usage] => Array
(
[used_memory] => 18420880
[free_memory] => 250014576
[wasted_memory] => 0
[current_wasted_percentage] => 0
)
[interned_strings_usage] => Array
(
[buffer_size] => 12582448
[used_memory] => 494840
[free_memory] => 12087608
[number_of_strings] => 10390
)
[opcache_statistics] => Array
(
[num_cached_scripts] => 0
[num_cached_keys] => 0
[max_cached_keys] => 32531
[hits] => 0
[start_time] => 1741540602
[last_restart_time] => 0
[oom_restarts] => 0
[hash_restarts] => 0
[manual_restarts] => 0
[misses] => 0
[blacklist_misses] => 0
[blacklist_miss_ratio] => 0
[opcache_hit_rate] => 0
)
[scripts] => Array
(
)
[jit] => Array
(
[enabled] => 1
[on] => 1
[kind] => 5
[opt_level] => 4
[opt_flags] => 6
[buffer_size] => 67108848
[buffer_free] => 67106144
)
)
Nếu opcache_get_status()
trả về một mảng với các giá trị như:
[opcache_enabled] => 1
(đã bật)[num_cached_scripts] > 0
(số lượng file đã cache)[memory_usage][used_memory] > 0
(đã sử dụng bộ nhớ)
Thì có nghĩa là OPcache đã cache các script PHP. Nếu num_cached_scripts
bằng 0, tức là OPcache chưa cache file nào.
PHP-FPM không sử dụng OPcache
Nếu đang chạy một web server (Apache/Nginx + PHP-FPM), OPcache chỉ hoạt động trong PHP-FPM chứ không hoạt động khi chạy script từ CLI (php -r
).
Bạn có thể tạo một file PHP để kiểm tra:
🔹 Cách kiểm tra OPcache có hoạt động trên Web không
Tạo file opcache_test.php
trong thư mục website của bạn (ví dụ /var/www/wiki.hoanghd.com/opcache_status.php
):
<?php
print_r(opcache_get_status());
?>
Sau đó truy cập:
https://wiki.hoanghd.com/opcache_status.php
Hoặc dùng trang OPcache GUI để quan sát trạng thái OPcache:
wget https://raw.githubusercontent.com/amnuts/opcache-gui/master/index.php -O /var/www/wiki.hoanghd.com/opcache.php

Sau đó truy cập https://wiki.hoanghd.com/opcache.php
để xem thông tin chi tiết. Nếu trên trình duyệt hiển thị num_cached_scripts > 0
, nghĩa là OPcache đang cache các script PHP trên web.
OPcache chỉ cache các file PHP đã được chạy ít nhất một lần. Thử mở một số trang của website (wiki.hoanghd.com
) rồi kiểm tra lại OPcache.
8. Kết Luận
Việc bật OPcache giúp cải thiện đáng kể hiệu suất xử lý PHP trên server sử dụng Nginx. Bạn chỉ cần cài đặt, tối ưu cấu hình và tích hợp với FastCGI Cache để tận dụng tối đa hiệu suất của OPcache. Nếu gặp bất kỳ lỗi nào, hãy kiểm tra log PHP và Nginx để khắc phục.
Chúc bạn thành công!