(本文地址:https://www.nzw6.com/35546.html)
Laravel Nginx配置文件
开头解决方案
在部署Laravel应用时,正确配置Nginx是确保应用稳定运行的关键。如何为Laravel项目配置Nginx,并提供多种思路以应对不同场景下的需求。
基础配置方案
最常用的配置方式如下:
nginx
server {
listen 80;
server_name yourdomain.com;
root /var/www/html/your-project/public;</p>
<pre><code>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/php7.4-fpm.sock; #根据PHP版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /.ht {
deny all;
}
}
优化性能的高级配置
为了提高性能,可以添加缓存和Gzip压缩设置:
nginx
server {
...</p>
<pre><code># Gzip压缩
gzip on;
gzip_types text/css application/javascript;
gzip_min_length 1000;
gzip_comp_level 5;
gzip_proxied any;
gzip_vary on;
# 静态文件缓存
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
}
# FastCGI缓存
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_valid 200 60m;
fastcgi_cache_use_stale error timeout invalid_header http_500;
}
安全强化配置
增强安全性是非常重要的:
nginx
server {
...</p>
<pre><code># 禁止访问敏感文件
location ~* (.env|.git|composer.(json|lock)|readme) {
deny all;
}
# 设置严格传输安全
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 内容安全策略
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';";
# XSS防护
add_header X-XSS-Protection "1; mode=block";
}
多域名支持配置
当需要支持多个域名时:
nginx
server {
listen 80;
server_name domain1.com www.domain1.com;
root /var/www/domain1/public;</p>
<pre><code>server {
listen 80;
server_name domain2.com www.domain2.com;
root /var/www/domain2/public;
}
}
建议根据实际需求选择合适的配置方案,并定期检查和优化配置文件。在修改配置后记得使用nginx -t
命令测试配置文件是否正确,然后再用systemctl reload nginx
使新配置生效。