插件窝 干货文章 如何利用NGINX和PM2构建安全的VPS环境

如何利用NGINX和PM2构建安全的VPS环境

安全 NGINX sudo 配置 866    来源:    2025-04-11

利用NGINX和PM2构建安全的VPS环境指南

1. 基础系统安全设置

1.1 系统更新与加固

# 更新系统软件包
sudo apt update && sudo apt upgrade -y

# 安装基础安全工具
sudo apt install -y fail2ban ufw unattended-upgrades

1.2 防火墙配置

# 启用防火墙
sudo ufw enable

# 基本规则设置
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

1.3 SSH安全加固

# 修改SSH配置文件 /etc/ssh/sshd_config
Port 2222  # 修改默认端口
PermitRootLogin no
PasswordAuthentication no  # 仅使用密钥认证
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2

2. NGINX安全配置

2.1 安装与基础配置

# 安装NGINX
sudo apt install -y nginx

# 创建专用用户和组
sudo groupadd webadmin
sudo useradd -g webadmin -d /nonexistent -s /usr/sbin/nologin webadmin

2.2 安全配置文件示例 (/etc/nginx/nginx.conf)

user webadmin webadmin;
worker_processes auto;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    server_tokens off;  # 隐藏NGINX版本信息
    autoindex off;      # 禁止目录列表

    # SSL安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

    # 其他安全头
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";
    add_header Referrer-Policy "strict-origin";
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com; img-src 'self' data: https://*.example.com";

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

2.3 站点配置示例

server {
    listen 80;
    server_name yourdomain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;

    root /var/www/yourdomain.com;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public";
    }

    # 限制请求方法
    if ($request_method !~ ^(GET|HEAD|POST)$) {
        return 405;
    }

    # 限制上传大小
    client_max_body_size 10M;
}

3. PM2应用管理安全

3.1 安装与基础配置

# 安装Node.js和PM2
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt install -y nodejs
sudo npm install -g pm2

3.2 安全启动应用

# 以非root用户启动应用
sudo -u webadmin pm2 start app.js --name "MyApp" --watch

# 设置PM2开机启动
pm2 startup
pm2 save

3.3 PM2安全配置

// ecosystem.config.js
module.exports = {
  apps: [{
    name: 'MyApp',
    script: 'app.js',
    instances: 'max',
    exec_mode: 'cluster',
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production',
      PORT: 3000,
      // 其他环境变量
    },
    // 安全相关配置
    uid: 'webadmin',
    gid: 'webadmin',
    pid: '/var/run/myapp.pid',
    out_file: '/var/log/myapp/out.log',
    error_file: '/var/log/myapp/error.log',
    merge_logs: true,
    log_date_format: 'YYYY-MM-DD HH:mm Z'
  }]
};

4. 综合安全措施

4.1 定期备份策略

# 示例备份脚本
#!/bin/bash
DATE=$(date +%Y-%m-%d)
BACKUP_DIR="/backups/$DATE"

mkdir -p $BACKUP_DIR

# 备份网站数据
tar -czf $BACKUP_DIR/website.tar.gz /var/www

# 备份NGINX配置
tar -czf $BACKUP_DIR/nginx.tar.gz /etc/nginx

# 备份PM2应用列表
pm2 save
tar -czf $BACKUP_DIR/pm2.tar.gz ~/.pm2

# 上传到远程存储
rclone copy $BACKUP_DIR remote:backups/$DATE

4.2 监控与日志分析

# 安装日志分析工具
sudo apt install -y logwatch

# 配置日志轮转
sudo nano /etc/logrotate.d/nginx
sudo nano /etc/logrotate.d/pm2

4.3 定期安全审计

# 安装安全审计工具
sudo apt install -y lynis

# 执行安全审计
sudo lynis audit system

5. 高级安全措施

5.1 应用层防火墙 (ModSecurity)

# 安装ModSecurity
sudo apt install -y libapache2-mod-security2

# 配置OWASP核心规则集
sudo git clone https://github.com/coreruleset/coreruleset /etc/nginx/modsec/
sudo cp /etc/nginx/modsec/crs-setup.conf.example /etc/nginx/modsec/crs-setup.conf

5.2 速率限制

# 在NGINX配置中添加
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

server {
    location / {
        limit_req zone=one burst=20 nodelay;
        # 其他配置
    }
}

5.3 使用Cloudflare或其他CDN增强安全

通过以上配置,您可以构建一个相对安全的VPS环境,结合NGINX作为反向代理和Web服务器,PM2作为Node.js应用进程管理器。请根据您的具体应用需求调整配置,并定期更新系统和软件以保持安全性。