温馨提示×

debian如何保护laravel安全

小樊
46
2026-09-29 09:42:41
栏目: 智能运维

在 Debian 上保护 Laravel 应用安全,通常需要系统层 + Web 层 + Laravel 自身三层防护。下面按实战角度给你一份比较完整的安全配置清单。


一、系统与用户安全

1. 使用专用用户运行应用

不要使用 root 或 www-data 直接跑 Laravel。

sudo adduser laravel
sudo usermod -aG www-data laravel

项目目录归属:

sudo chown -R laravel:www-data /var/www/laravel

2. 最小权限原则

sudo chmod -R 755 /var/www/laravel
sudo chmod -R 775 storage bootstrap/cache

3. 禁用 root SSH 登录

sudo nano /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
sudo systemctl restart ssh

4. 开启防火墙

sudo apt install ufw
sudo ufw allow OpenSSH
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable

二、Web 服务安全(Nginx / Apache)

Nginx 推荐配置

server {
    listen 443 ssl;
    server_name example.com;

    root /var/www/laravel/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    }

    # 禁止访问敏感文件
    location ~ /\.(?!well-known).* {
        deny all;
    }

    location ~ /(vendor|storage|bootstrap)/.* {
        deny all;
    }
}

强制 HTTPS

使用 Let’s Encrypt:

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx

三、PHP 安全配置

编辑 php.ini:

sudo nano /etc/php/8.2/fpm/php.ini

建议:

expose_php = Off
display_errors = Off
log_errors = On
allow_url_fopen = Off
disable_functions = exec,passthru,shell_exec,system,proc_open,popen

重启 PHP:

sudo systemctl restart php8.2-fpm

四、Laravel 自身安全

1. 关闭调试模式

.env

APP_DEBUG=false
APP_ENV=production

2. 保护 .env 文件

确保 Web 无法直接访问:

location ~ /\.env {
    deny all;
}

3. 使用官方加密密钥

php artisan key:generate

4. 开启 HTTPS 强制

App\Http\Middleware\TrustProxies

protected $proxies = '*';

或中间件:

\App\Http\Middleware\ForceHttps::class

5. 定期更新依赖

composer update
composer audit

五、数据库安全

  • 使用独立数据库用户
  • 禁止远程 root 登录
  • 定期备份
mysqldump -u user -p db > backup.sql

六、日志与监控

sudo apt install fail2ban
sudo systemctl enable fail2ban

查看异常:

sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/www/laravel/storage/logs/laravel.log

七、推荐安全工具

  • Laravel Shift Security Check
  • composer audit
  • OWASP ZAP
  • ClamAV(防恶意文件)

如果你愿意,我可以:

  • 给你一份 Debian + Nginx + Laravel 安全模板
  • 或针对 生产环境 / 内网环境 给不同方案
  • 或帮你检查现有服务器配置是否安全

你可以直接说你的环境(Debian 版本 / Nginx 或 Apache / PHP 版本)。

0 踩