laravel nginx配置文件

2025-03-20 11

(本文地址: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使新配置生效。

Image

1. 本站所有资源来源于用户上传和网络,因此不包含技术服务请大家谅解!如有侵权请邮件联系客服!cheeksyu@vip.qq.com
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
4. 如果您也有好的资源或教程,您可以投稿发布,成功分享后有积分奖励和额外收入!
5.严禁将资源用于任何违法犯罪行为,不得违反国家法律,否则责任自负,一切法律责任与本站无关

源码下载