在 Debian 上保护 Laravel 应用,通常从 系统层、Web 层、Laravel 层、数据库层、运维层 几个维度来做。下面给你一套实战型安全清单,适合生产环境。
sudo apt update && sudo apt upgrade -y
adduser deploy
usermod -aG sudo deploy
编辑:
sudo nano /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
sudo systemctl restart ssh
✅ 使用 SSH Key 登录
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
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;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
# 禁止访问敏感文件
location ~ /\.(env|git) {
deny all;
}
location ~ ^/(\.env|composer\.json|composer\.lock|artisan) {
deny all;
}
}
.env这是最重要的一条
location ~ /\.env {
deny all;
}
或系统级:
chmod 600 .env
APP_ENV=production
APP_DEBUG=false
php artisan config:cache
php artisan route:cache
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx
Laravel 中强制 HTTPS:
\URL::forceScheme('https');
php artisan telescope:clear # 如果用 Telescope
php artisan cache:clear
sudo chown -R www-data:www-data /var/www/laravel
sudo chmod -R 755 /var/www/laravel
sudo chmod -R 777 storage bootstrap/cache
✅ 推荐(更安全):
sudo setfacl -R -m u:www-data:rwX storage bootstrap/cache
DROP USER 'root'@'%';
CREATE USER 'laravel'@'localhost' IDENTIFIED BY '强密码';
GRANT SELECT,INSERT,UPDATE,DELETE ON laravel.* TO 'laravel'@'localhost';
bind-address = 127.0.0.1
✅ 使用 Eloquent / Query Builder
❌ 避免 raw SQL
Blade 默认转义:
{{ $user->name }}
❌ 不要用:
{!! $user->input !!}
<form method="POST">
@csrf
</form>
$request->validate([
'file' => 'file|mimes:jpg,png,pdf|max:2048',
]);
存储到 storage/app 而不是 public
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
Route::middleware(['throttle:60,1'])->group(function () {
//
});
sudo apt install fail2ban
Laravel 日志:
LOG_CHANNEL=stack
❌ .env 可访问
❌ APP_DEBUG=true 在生产环境
❌ storage/ 可浏览器访问
❌ 使用 root 运行 PHP-FPM
❌ 数据库用 root 连接 Laravel
✅ Debian 更新
✅ SSH Key + 禁用 root
✅ Nginx 禁止 .env
✅ HTTPS
✅ APP_DEBUG=false
✅ 正确文件权限
✅ 数据库最小权限
✅ 防火墙 + fail2ban
如果你愿意,我可以:
你现在用的是 Nginx 还是 Apache?PHP 几版本?