在 Debian 上保护 Laravel 应用安全,通常需要系统层 + Web 层 + Laravel 自身三层防护。下面按实战角度给你一份比较完整的安全配置清单。
不要使用 root 或 www-data 直接跑 Laravel。
sudo adduser laravel
sudo usermod -aG www-data laravel
项目目录归属:
sudo chown -R laravel:www-data /var/www/laravel
sudo chmod -R 755 /var/www/laravel
sudo chmod -R 775 storage bootstrap/cache
sudo nano /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
sudo systemctl restart ssh
sudo apt install ufw
sudo ufw allow OpenSSH
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable
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;
}
}
使用 Let’s Encrypt:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx
编辑 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
.env
APP_DEBUG=false
APP_ENV=production
确保 Web 无法直接访问:
location ~ /\.env {
deny all;
}
php artisan key:generate
App\Http\Middleware\TrustProxies
protected $proxies = '*';
或中间件:
\App\Http\Middleware\ForceHttps::class
composer update
composer audit
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
如果你愿意,我可以:
你可以直接说你的环境(Debian 版本 / Nginx 或 Apache / PHP 版本)。