# 定期更新系统
sudo apt update && sudo apt upgrade -y # Debian/Ubuntu
sudo yum update -y # CentOS/RHEL
# 使用UFW (Ubuntu)
sudo ufw enable
sudo ufw default deny incoming
sudo ufw allow 22/tcp # SSH
sudo ufw allow 443/tcp # HTTPS
# 或者使用firewalld (CentOS/RHEL)
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
推荐使用Nginx或Apache的最新稳定版本:
# Nginx安装
sudo apt install nginx -y # Debian/Ubuntu
sudo yum install nginx -y # CentOS/RHEL
server {
listen 443 ssl http2;
server_name yourdomain.com;
# SSL配置
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384...';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 安全头
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'self'";
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
# 其他安全设置
server_tokens off;
client_max_body_size 1m;
location / {
# 应用特定的安全配置
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 禁用敏感文件访问
location ~ /\.(?!well-known).* {
deny all;
}
location ~* \.(log|sql|conf|env)$ {
deny all;
}
}
使用Let's Encrypt免费证书:
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com
# 设置自动续期
sudo certbot renew --dry-run
# 添加到crontab
0 12 * * * /usr/bin/certbot renew --quiet
# Nginx日志配置
access_log /var/log/nginx/access.log combined buffer=32k flush=5m;
error_log /var/log/nginx/error.log warn;
# 安装和运行Lynis安全审计工具
sudo apt install lynis -y
sudo lynis audit system
nikto -h yourdomain.com -ssl
# 示例备份脚本
tar -czvf /backups/web-$(date +%Y%m%d).tar.gz /var/www/html
# 加密备份
gpg --encrypt --recipient your@email.com /backups/web-$(date +%Y%m%d).tar.gz
通过以上步骤,您可以建立一个高度安全的Web接口环境。请记住,安全是一个持续的过程,需要定期审查和更新安全措施以应对新的威胁。