Rewrite e Performance
Aula 4 de 5
mod_rewrite Avançado
Estrutura de RewriteRule
RewriteRule Pattern Substitution [Flags]
| Flag | Significado |
|---|---|
| R=301 | Redirect permanente |
| R=302 | Redirect temporário |
| F | Forbidden (403) |
| L | Last rule (última regra) |
| QSA | Query String Append |
| NC | No Case (case-insensitive) |
| OR | Or (combina condições) |
| PT | Pass Through |
RewriteCond - Condicionais
RewriteEngine On
# Redirecionar apenas em dia específico
RewriteCond %{TIME_WDAY} ^06$ # Sábado
RewriteCond %{TIME_HOUR} ^(08|09|10)$
RewriteRule ^/$ /manutencao.html [R=302,L]
# Baseada em User-Agent
RewriteCond %{HTTP_USER_AGENT} "android|iphone|ipad" [NC]
RewriteRule ^(.*)$ mobile/$1 [L]
# Baseada em query string
RewriteCond %{QUERY_STRING} (^|&)id=[0-9]+(&|$)
RewriteRule ^produto\.php$ /produto/%{QUERY_STRING:id} [R=301,L]
# Combinar condições (AND implícito)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
# OR explícito
RewriteCond %{HTTP_COOKIE} theme=dark [NC,OR]
RewriteCond %{QUERY_STRING} ^dark=true$
RewriteRule ^(.*)$ dark/$1 [L]
Flags R, F, D
# R=301 - Redirect Permanente (SEO)
RewriteRule ^categoria/(.*)$ /produtos/$1 [R=301,L]
# R=302 - Redirect Temporário
RewriteRule ^promocao/(.*)$ /landing-page.php?prod=$1 [R=302,L]
# F - Forbidden (bloquear acesso)
RewriteRule \.(env|git|sql|log|md)$ - [F,L]
RewriteRule ^vendor/ - [F,L]
# NC - Case Insensitive
RewriteRule ^Produto/(.*)$ /produto/$1 [R=301,NC,L]
# QSA - Query String Append
RewriteRule ^busca/(.*)$ search.php?q=$1 [QSA,L]
# /busca/apache?page=2 -> search.php?q=apache&page=2
# PT - Pass Through (para outros handlers)
RewriteRule ^(.*\.php)$ $1 [PT,L]
mod_alias vs mod_rewrite
mod_alias (simples, direto)
# Alias - mapeamento simples de URL para diretório
Alias /manual /usr/share/doc/manual
# AliasMatch - com regex
AliasMatch ^/blog/([0-9]{4})/([0-9]{2})/(.*)$ /var/www/blog/$1/$2/$3
# Redirect - redirecionamento simples
Redirect /antiga.html /nova.html
RedirectMatch 301 ^/noticias/(.*)$ https://blog.exemplo.com/$1
Quando usar cada um
| Situação | Ferramenta |
|---|---|
| Mapear URL para diretório fixo | Alias |
| Redirecionamento simples | Redirect |
| Lógica condicional complexa | mod_rewrite |
| Forçar HTTPS ou WWW | mod_rewrite |
| Manutenção (Redirect temporário) | Redirect 302 |
.htaccess e Performance
# Evite isso no .htaccess (lento):
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
# Prefira no VirtualHost (mais rápido):
# Mesmas regras, mas sem ler .htaccess a cada requisição
# Performance: AllowOverride None em diretórios sem .htaccess
# No VirtualHost:
<Directory /var/www/site/static>
AllowOverride None
Options -Indexes
Require all granted
</Directory>
# .htaccess só onde necessário
<Directory /var/www/site/dynamic>
AllowOverride FileInfo
Options -Indexes
Require all granted
</Directory>
Caching com mod_cache
# Habilitar cache
sudo a2enmod cache cache_disk cache_socache
# Cache por disco
<IfModule mod_cache_disk.c>
CacheRoot /var/cache/apache2/
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
CacheMaxFileSize 1000000
CacheMinFileSize 1
</IfModule>
# Cache por shared memory (mais rápido)
<IfModule mod_cache_socache.c>
CacheEnable socache /
CacheSocache shmcb:${APACHE_RUN_DIR}/cache_socache(512000)
CacheDefaultExpire 3600
</IfModule>
Compressão com mod_deflate
# Configuração completa de compressão
<IfModule mod_deflate.c>
# Comprimir tipos MIME específicos
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css text/javascript
AddOutputFilterByType DEFLATE application/javascript application/json
AddOutputFilterByType DEFLATE application/xml application/rss+xml
AddOutputFilterByType DEFLATE image/svg+xml font/ttf font/opentype
# Não comprimir conteúdo já compactado
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|zip|gz|bz2|xz)$ no-gzip dont-vary
# Evitar problemas com proxies antigos
Header append Vary User-Agent env=!dont-vary
# Nível de compressão (1-9)
DeflateCompressionLevel 6
# Tamanho mínimo para comprimir
DeflateBufferSize 8096
</IfModule>
Expires e Cache-Control
<IfModule mod_expires.c>
ExpiresActive On
# Default
ExpiresDefault "access plus 1 month"
# HTML/XML: sem cache
ExpiresByType text/html "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
# Assets: cache longo
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
# Fontes
ExpiresByType font/ttf "access plus 1 year"
ExpiresByType font/woff "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>
# Cache-Control via mod_headers
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=31536000, public, immutable"
</FilesMatch>
<FilesMatch "\.(html|htm|xml)$">
Header set Cache-Control "max-age=0, private, must-revalidate"
</FilesMatch>
<FilesMatch "\.(json)$">
Header set Cache-Control "no-cache, no-store, must-revalidate"
</FilesMatch>
KeepAlive e MPM Tuning
# Verificar MPM ativo
sudo apache2ctl -V | grep -i mpm
MPM Prefork
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
</IfModule>
MPM Worker
<IfModule mpm_worker_module>
StartServers 3
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 200
MaxConnectionsPerChild 10000
</IfModule>
MPM Event (recomendado)
<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 200
MaxConnectionsPerChild 10000
</IfModule>
# KeepAlive optimization
KeepAlive On
KeepAliveTimeout 2
MaxKeepAliveRequests 100
Lab: Performance Tuning Completo
Configure um VirtualHost otimizado para performance.
# 1. Verificar MPM atual
sudo apache2ctl -V | grep -i mpm
# 2. Trocar para MPM Event (se prefork)
sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2
# 3. Habilitar módulos de performance
sudo a2enmod expires headers deflate cache cache_disk
sudo systemctl reload apache2
# 4. Criar configuração de performance
cat << 'PERF' | sudo tee /etc/apache2/conf-available/performance.conf
# KeepAlive
KeepAlive On
KeepAliveTimeout 2
MaxKeepAliveRequests 100
# Timeouts
Timeout 60
RequestReadTimeout header=20-40,MinRate=500 body=20-40,MinRate=500
# MPM Event tuning
<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 200
MaxConnectionsPerChild 10000
</IfModule>
# Compressão
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css application/javascript
AddOutputFilterByType DEFLATE application/json application/xml
DeflateCompressionLevel 6
</IfModule>
# Cache de arquivos estáticos
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/* "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
PERF
# 5. Habilitar e aplicar
sudo a2enconf performance
sudo apache2ctl configtest
sudo systemctl restart apache2
# 6. Testar performance
curl -I http://localhost/assets/style.css
# Verificar headers: Cache-Control, Expires, Content-Encoding
Otimização de performance é um processo contínuo. Monitore os logs de acesso, ajuste os parâmetros MPM conforme o tráfego real e prefira configurações no VirtualHost em vez de .htaccess para máximo desempenho.