Cấu hình nginx full cho dự án Laravel

 🗂 Cấu trúc Laravel mặc định cần:


/var/www/your-laravel-app/ └── public/ └── index.php

Laravel phải được trỏ đến thư mục /public – nếu không sẽ bị lộ .env, routes/web.php,...


📄 File cấu hình hoàn chỉnh

Đặt tại: /etc/nginx/sites-available/your-app.conf

nginx:
server { listen 80; server_name your-domain.com www.your-domain.com; root /var/www/your-laravel-app/public; index index.php index.html index.htm; # Ghi log access_log /var/log/nginx/your-app_access.log; error_log /var/log/nginx/your-app_error.log; # Xử lý request chính location / { try_files $uri $uri/ /index.php?$query_string; } # Xử lý PHP thông qua PHP-FPM socket location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.2-fpm.sock; # Tùy phiên bản PHP fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # Tăng bảo mật: không cho truy cập file ẩn hoặc nguy hiểm location ~ /\. { deny all; } # Tắt truy cập đến cấu trúc folder phía Laravel location ~* \.(env|git|htaccess|log)$ { deny all; } # Nén nội dung để tăng tốc độ gzip on; gzip_types text/plain application/json application/javascript text/css; # Tăng hiệu năng file tĩnh location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf)$ { expires 30d; access_log off; } }

🔗 Bật cấu hình:

bash
ln -s /etc/nginx/sites-available/your-app.conf /etc/nginx/sites-enabled/ nginx -t && systemctl reload nginx

Vì nginx chỉ đọc file trong sites-enabled nên cần phải đồng bộ từ sites-available qua
sites-enabled bằng ln -s

Vì vậy:
your-site.conf trong sites-available là file gốc
sites-enabled chứa shortcut trỏ về file gốc → giúp dễ quản lý.

🧠 Giải thích quan trọng từng phần:

DòngGiải thích
listen 80;Cấu hình server lắng nghe HTTP
server_nameTên miền cần phục vụ
rootLaravel chạy trong public, không nên dùng root gốc
try_filesKiểm tra file vật lý trước, nếu không thì chạy index.php
fastcgi_passGửi request .php tới PHP-FPM (tùy bản PHP: php8.2-fpm.sock, php8.1…)
fastcgi_paramRất quan trọng! Laravel cần dòng này để biết file thực sự là gì
gzipBật nén, tối ưu tốc độ
location ~ /\.envCấm truy cập .env, .git, .htaccess
`location ~* .(jpgjs

Post a Comment

Previous Post Next Post