Nginx потребляет значительно меньше памяти и обрабатывает статику в разы быстрее Apache. Переход оправдан при высоких нагрузках или ограниченных ресурсах сервера. Главная сложность — конвертация .htaccess в синтаксис location-блоков Nginx.
Apache vs Nginx: ключевые различия
| Аспект | Apache | Nginx |
|---|---|---|
| Архитектура | Process/Thread | Event-driven (асинхронный) |
| Статические файлы | Медленнее | В 2–4 раза быстрее |
| Потребление RAM | Больше (fork per request) | Меньше (worker processes) |
| PHP | mod_php (встроен) | Только через PHP-FPM |
| .htaccess | Поддерживается | Не поддерживается |
| Конфигурация | По-директорийно (.htaccess) | Централизованная |
Установка Nginx и PHP-FPM
# Установить Nginx и PHP-FPM
apt install nginx php8.3-fpm -y
# Остановить Apache
systemctl stop apache2
systemctl disable apache2
# Запустить Nginx
systemctl enable --now nginx
Конвертация Apache Virtual Host → Nginx Server Block
# Apache VirtualHost (было)
ServerName example.com
DocumentRoot /var/www/html
DirectoryIndex index.php index.html
AllowOverride All
# Nginx Server Block (стало)
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
Конвертация .htaccess правил
# .htaccess: Redirect (было)
Redirect 301 /old-page.html /new-page
# Nginx (стало)
location = /old-page.html {
return 301 /new-page;
}
# .htaccess: RewriteRule
RewriteRule ^products/([0-9]+)$ product.php?id=$1 [L]
# Nginx:
location ~ ^/products/([0-9]+)$ {
rewrite ^/products/([0-9]+)$ /product.php?id=$1 last;
}
# .htaccess: Deny access to directory
Options -Indexes
# Nginx:
location /private/ {
deny all;
}
# .htaccess: Custom error pages
ErrorDocument 404 /404.php
# Nginx:
error_page 404 /404.php;
Nginx для WordPress (полный конфиг)
server {
listen 443 ssl http2;
server_name example.com www.example.com;
root /var/www/wordpress;
# Gzip сжатие
gzip on;
gzip_types text/css application/javascript text/html;
# Статические файлы — кеш
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_read_timeout 300;
include fastcgi_params;
}
}
Конвертер .htaccess: Используйте онлайн-инструмент winginx.com/htaccess для автоматической конвертации .htaccess-правил в Nginx-синтаксис. Затем обязательно проверьте результат вручную.
.htaccess в Nginx игнорируется — файлы остаются на диске, но не обрабатываются. Если сайт использует .htaccess для редиректов или защиты директорий, все правила нужно перенести в Nginx-конфиг вручную.