A seguir está um guia prático e testado para otimizar Apache + Nginx em proxy reverso focando alto tráfego, baixo TTFB e uso eficiente de CPU/RAM — exatamente o cenário que você usa hoje (Apache + Nginx + PHP-FPM em VPS).
1️⃣ Arquitetura correta (base de tudo)
Internet ↓ Nginx (porta 80/443) ↓ Apache (porta 8080) ↓ PHP-FPM
Por quê?
- Nginx lida com conexões simultâneas, SSL e arquivos estáticos
- Apache só processa PHP/dinâmica
- PHP-FPM trabalha isolado e previsível
2️⃣ Nginx — Ajustes essenciais para alto tráfego
🔹 Worker e conexões
worker_processes auto;
worker_rlimit_nofile 200000;
events {
worker_connections 8192;
multi_accept on;
use epoll;
}
Regra prática:
worker_processes × worker_connections ≥ conexões simultâneas esperadas
🔹 Buffers e proxy
proxy_buffering on; proxy_buffers 32 64k; proxy_buffer_size 128k; proxy_busy_buffers_size 256k;
Reduz TTFB e evita gargalos no Apache.
🔹 Timeouts
proxy_connect_timeout 30s; proxy_send_timeout 60s; proxy_read_timeout 60s; send_timeout 60s;
🔹 Gzip (ou Brotli se disponível)
gzip on;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_types
text/plain
text/css
application/json
application/javascript
text/xml
application/xml
image/svg+xml;
🔹 Cache de arquivos estáticos
location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff2?)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
👉 Apache não deve servir arquivos estáticos.
3️⃣ Apache — Ajustes críticos
🔹 Use SOMENTE MPM Event
apachectl -M | grep mpm
Se não for mpm_event, altere:
LoadModule mpm_event_module modules/mod_mpm_event.so
🔹 Configuração MPM Event (alta performance)
<IfModule mpm_event_module>
ServerLimit 32
StartServers 4
MinSpareThreads 64
MaxSpareThreads 256
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 800
MaxConnectionsPerChild 5000
</IfModule>
📌 Ajuste MaxRequestWorkers conforme RAM disponível.
🔹 KeepAlive (curto)
KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 2
🔹 Desative módulos inúteis
apachectl -M
Remova:
- autoindex
- status
- negotiation
- proxy (se não usar)
- perl / python
4️⃣ Comunicação Nginx → Apache (essencial)
Apache não deve escutar na 80/443:
Listen 127.0.0.1:8080
Nginx:
proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme;
5️⃣ PHP-FPM — Onde muita gente erra
🔹 pm = ondemand (produção)
pm = ondemand pm.max_children = 80 pm.process_idle_timeout = 10s pm.max_requests = 500
📌 Cálculo correto:
RAM disponível ÷ consumo médio por processo PHP
Exemplo:
8 GB livres ÷ 80 MB ≈ 100 children
🔹 OPcache (OBRIGATÓRIO)
opcache.enable=1 opcache.memory_consumption=256 opcache.interned_strings_buffer=32 opcache.max_accelerated_files=100000 opcache.validate_timestamps=0
6️⃣ Cache no Nginx (nível avançado 🚀)
🔹 FastCGI Cache (WordPress voa)
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=WP:256m inactive=60m;
fastcgi_cache WP; fastcgi_cache_valid 200 301 302 60m; fastcgi_cache_use_stale error timeout invalid_header updating;
👉 Reduz CPU, PHP e MySQL drasticamente.
7️⃣ Kernel e sistema (muito importante)
net.core.somaxconn = 65535 net.ipv4.tcp_fin_timeout = 15 net.ipv4.tcp_tw_reuse = 1 fs.file-max = 1000000
Aplicar:
sysctl -p
8️⃣ Monitoramento (não otimiza no escuro)
Ferramentas recomendadas:
htopngxtopapachetopphp-fpm_exporternetdata
9️⃣ Checklist rápido ✅
✔ Nginx na frente
✔ Apache apenas para PHP
✔ MPM Event ativo
✔ PHP-FPM ondemand
✔ OPcache ativo
✔ Cache estático e FastCGI
✔ KeepAlive curto
✔ Kernel tunado
Configs prontas (Nginx + Apache + PHP-FPM)
Abaixo estão configs prontas, organizadas e testadas para alto tráfego, considerando 8 vCPU / 12 GB RAM, CloudLinux, Nginx (proxy reverso) + Apache + PHP-FPM.
🎯 Objetivo: baixo TTFB, alto número de conexões, uso eficiente de RAM/CPU
🔧 Compatível com WordPress, WooCommerce e sites dinâmicos
🟢 1️⃣ NGINX (Proxy Reverso)
📁 /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_rlimit_nofile 200000;
events {
worker_connections 8192;
use epoll;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;
keepalive_requests 1000;
client_max_body_size 128m;
server_tokens off;
## Buffers
proxy_buffering on;
proxy_buffers 32 64k;
proxy_buffer_size 128k;
proxy_busy_buffers_size 256k;
## Timeouts
proxy_connect_timeout 30s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
## GZIP
gzip on;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_types
text/plain
text/css
application/json
application/javascript
text/xml
application/xml
image/svg+xml;
## Logs
access_log off;
error_log /var/log/nginx/error.log warn;
include /etc/nginx/conf.d/*.conf;
}
🔹 VirtualHost padrão (proxy para Apache)
📁 /etc/nginx/conf.d/site.conf
server {
listen 80;
server_name example.com www.example.com;
root /home/example/domains/example.com/public_html;
index index.php index.html;
## Arquivos estáticos (Nginx)
location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff2?|ttf)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
try_files $uri =404;
}
## Proxy para Apache
location / {
try_files $uri @apache;
}
location @apache {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
🔵 2️⃣ APACHE (MPM EVENT)
📁 /etc/httpd/conf.modules.d/00-mpm.conf
LoadModule mpm_event_module modules/mod_mpm_event.so
📁 /etc/httpd/conf/httpd.conf (ou custom no DirectAdmin)
ServerTokens Prod ServerSignature Off Timeout 60 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 2 Listen 127.0.0.1:8080
🔹 MPM Event (alto tráfego)
📁 /etc/httpd/conf.d/mpm_event.conf
<IfModule mpm_event_module>
ServerLimit 32
StartServers 4
MinSpareThreads 64
MaxSpareThreads 256
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 800
MaxConnectionsPerChild 5000
</IfModule>
✔ Suporta milhares de conexões simultâneas
✔ Apache só processa PHP (sem estáticos)
🟣 3️⃣ PHP-FPM (CloudLinux)
📁 /usr/local/php83/etc/php-fpm.d/example.conf
[example] user = example group = example listen = /usr/local/php83/sockets/example.sock listen.owner = example listen.group = nginx listen.mode = 0660 pm = ondemand pm.max_children = 80 pm.process_idle_timeout = 10s pm.max_requests = 500 request_terminate_timeout = 120s php_admin_value[memory_limit] = 256M php_admin_value[max_execution_time] = 120 php_admin_value[post_max_size] = 128M php_admin_value[upload_max_filesize] = 128M
📌 Cálculo aplicado:
~80 MB por processo × 80 children ≈ 6.4 GB
Seguro para VPS 12 GB.
🔹 OPcache (OBRIGATÓRIO)
📁 /usr/local/php83/etc/php.d/10-opcache.ini
opcache.enable=1 opcache.enable_cli=0 opcache.memory_consumption=256 opcache.interned_strings_buffer=32 opcache.max_accelerated_files=100000 opcache.validate_timestamps=0 opcache.revalidate_freq=0 opcache.fast_shutdown=1
⚙️ 4️⃣ Kernel (sysctl)
📁 /etc/sysctl.d/99-performance.conf
net.core.somaxconn = 65535 net.ipv4.tcp_fin_timeout = 15 net.ipv4.tcp_tw_reuse = 1 fs.file-max = 1000000
Aplicar:
sysctl --system
✅ 5️⃣ Checklist final
✔ Nginx serve estáticos
✔ Apache só PHP
✔ MPM Event ativo
✔ PHP-FPM ondemand
✔ OPcache configurado
✔ KeepAlive curto
✔ Proxy otimizado
Clique aqui e consulte nossos planos de Gerenciamento de Servidor
