Шаблон nginx конфига
Laravel + PHP-FPM 8.2
Конфигурация nginx для Laravel-приложения с PHP-FPM 8.2. Паттерн Front Controller через index.php, запрет доступа к папкам vendor/storage/config, кэширование статики и защита чувствительных файлов.
Пример конфига
nginx.conf
server {
listen 80;
listen [::]:80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
# Корень Laravel — обязательно /public, не корень проекта!
root /var/www/laravel/public;
index index.php index.html;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
server_tokens off;
client_max_body_size 10m;
access_log /var/log/nginx/laravel-access.log combined;
error_log /var/log/nginx/laravel-error.log warn;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
gzip on;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript image/svg+xml;
# Front Controller: всё через index.php
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP через PHP-FPM
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
fastcgi_read_timeout 60s;
}
# Кэш статики
location ~* \.(jpg|jpeg|gif|png|ico|css|js|woff2|woff|ttf|svg)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
# Запрет доступа к служебным директориям Laravel
location ~ ^/(vendor|storage|bootstrap/cache|config|database|routes|tests)/ {
deny all;
return 404;
}
location ~ /\.(env|git|htaccess) {
deny all;
}
error_page 404 /index.php;
error_page 500 502 503 504 /50x.html;
location = /50x.html { root /usr/share/nginx/html; }
}
Как настроить
-
Установите PHP-FPM: apt install php8.2-fpm php8.2-mbstring php8.2-xml php8.2-curl
-
Настройте права: chown -R www-data:www-data /var/www/laravel && chmod -R 755 /var/www/laravel/storage
-
Убедитесь что root указывает на /var/www/laravel/public (не на корень проекта!)
-
Настройте .env: APP_URL=https://example.com
-
Запустите PHP-FPM: systemctl start php8.2-fpm
-
Скопируйте конфиг в nginx, проверьте (nginx -t) и перезагрузите