在 Ubuntu + ThinkPHP 环境下,防止黑客攻击需要从 系统层、Web服务层、ThinkPHP框架层、代码层、运维层 多方面入手。下面给你一套实战级防护方案(以 ThinkPHP 5 / 6 为主,也适用于 8)。
# 不要用 root 运行 web
useradd -m www
Nginx / PHP-FPM 使用 www 用户运行。
ufw allow 22
ufw allow 80
ufw allow 443
ufw enable
vim /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
使用 SSH 密钥登录
apt update && apt upgrade -y
location ~ /\. {
deny all;
}
location ~* /(runtime|vendor|config|env)/ {
deny all;
}
location ~* \.(log|sql|ini|env)$ {
deny all;
}
autoindex off;
client_max_body_size 8m;
.env
APP_DEBUG = false
Nginx:
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ ^/.*\.php$ {
# 只允许 index.php
if ($fastcgi_script_name !~ ^/index.php$) {
return 403;
}
}
// middleware
\think\middleware\CheckCsrfToken::class
表单:
<input type="hidden" name="__token__" value="{:token()}">
❌ 错误:
Db::query("SELECT * FROM user WHERE id = $id");
✅ 正确:
Db::name('user')->where('id', $id)->find();
input('post.content', '', 'htmlspecialchars');
或使用中间件统一过滤。
validate(['file' => 'fileSize:1024000|fileExt:jpg,png'])
保存路径 不要在前端可控目录
Route::get('user/profile', 'User/profile');
禁止:
Route::any(':controller/:action', ':controller/:action');
composer update topthink/framework
⚠️ 以下版本极危险:
rm public/.htaccess.bak
rm think
tail -f /var/log/nginx/access.log
tail -f /var/log/php7.4-fpm.log
apt install fail2ban
apt install aide
| 攻击方式 | 防御 |
|---|---|
| SQL注入 | ORM / 参数绑定 |
| XSS | 输出转义 |
| CSRF | Token |
| 文件上传 | 后缀+内容校验 |
| RCE | 升级框架 |
| 目录遍历 | Nginx 限制 |
| 暴力破解 | Fail2ban |
如果你愿意,我可以: ✅ 帮你 检查 ThinkPHP 是否存在漏洞 ✅ 给你一套 Nginx 完整安全配置 ✅ 按你的 ThinkPHP 版本定制防护方案
你用的是 ThinkPHP 几?Ubuntu 几?