Laravel Nginx 配置优化指南
基础优化配置
server {
listen 80;
server_name yourdomain.com;
root /var/www/laravel/public;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
性能优化配置
1. 启用Gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
2. 静态文件缓存
location ~* \.(jpg|jpeg|gif|png|css|js|ico|webp|svg)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
access_log off;
}
3. PHP-FPM优化
location ~ \.php$ {
fastcgi_buffer_size 128k;
fastcgi_buffers 256 16k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
fastcgi_read_timeout 300;
# 其他PHP配置...
}
4. 禁用不必要的日志记录
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
log_not_found off;
access_log off;
}
安全优化配置
1. 隐藏Nginx版本信息
server_tokens off;
2. 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";
3. 启用XSS保护
add_header X-XSS-Protection "1; mode=block";
4. 防止MIME类型嗅探
add_header X-Content-Type-Options nosniff;
Laravel特定优化
1. 优化路由缓存
php artisan route:cache
2. 配置环境缓存
php artisan config:cache
3. 视图缓存
php artisan view:cache
完整优化示例
server {
listen 80;
server_name yourdomain.com;
root /var/www/laravel/public;
index index.php index.html index.htm;
# 安全头
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options nosniff;
server_tokens off;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 静态文件缓存
location ~* \.(jpg|jpeg|gif|png|css|js|ico|webp|svg)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
access_log off;
}
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
# PHP性能优化
fastcgi_buffer_size 128k;
fastcgi_buffers 256 16k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
fastcgi_read_timeout 300;
}
location ~ /\.ht {
deny all;
}
# 禁用不必要的日志
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
log_not_found off;
access_log off;
}
}
优化后的检查步骤
- 测试配置语法是否正确:
sudo nginx -t
- 重新加载Nginx配置:
sudo systemctl reload nginx
- 使用工具测试性能改进:
- Google PageSpeed Insights
- GTmetrix
- WebPageTest
这些优化配置可以根据具体服务器环境和Laravel应用需求进行调整。