Nginx 是一款强大的开源反向代理服务器,用于提供高性能的 Web 服务。为了确保服务器的安全性和性能,我们将介绍一系列安全实践和性能调优的指南,使你的 Nginx 服务器更加可靠和高效。

安全实践

1. Web 应用程序防火墙(WAF)

集成 ModSecurity

ModSecurity 是一个强大的开源 Web 应用程序防火墙,可用于阻止各种攻击。以下是集成 ModSecurity 到 Nginx 的步骤:

  • 安装依赖:
sudo apt-get install -y libpcre3 libpcre3-dev libssl-dev
  • 下载、编译和安装 ModSecurity:
git clone --depth 1 -b v3/master --single-branch https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
./build.sh
./configure
make
sudo make install
  • 编译 Nginx 以支持 ModSecurity:
wget http://nginx.org/download/nginx-1.20.1.tar.gz
tar -zxvf nginx-1.20.1.tar.gz
cd nginx-1.20.1

./configure --with-compat --add-dynamic-module=../ModSecurity/nginx/modsecurity --with-http_ssl_module

make
sudo make install
  • 配置 Nginx 使用 ModSecurity:
http {
    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;

    server {
        location / {
            modsecurity_rules enable;
            # 其他配置...
        }
    }
}

详细的 ModSecurity 规则配置可根据需求进行调整。

2. 防盗链

配置防盗链规则

server {
    listen 80;
    server_name your_domain.com;

    location / {
        valid_referers blocked your_domain.com;
        if ($invalid_referer) {
            return 403;
        }

        # 其他配置...
    }
}

3. 访问限流

限制每个 IP 的请求速率

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

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

4. 限制连接速率

限制每个 IP 的并发连接数

http {
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    server {
        location / {
            limit_conn addr 10;
            # 其他配置...
        }
    }
}

5. 隐藏版本信息

禁用 Nginx 版本信息

http {
    server_tokens off;
    # 其他配置...
}

性能调优

1. 启用 Gzip 压缩

减小传输内容的大小

http {
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    # 其他配置...
}

2. 启用 Keepalive

增加连接的重用率

http {
    keepalive_timeout 15;
    # 其他配置...
}

3. 启用 SSL Session 缓存

提高 SSL 连接的性能

http {
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    # 其他配置...
}

4. 启用 FastCGI 缓存

提高动态内容的性能

http {
    fastcgi_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

    server {
        location ~ \.php$ {
            fastcgi_cache my_cache;
            # 其他配置...
        }
    }
}

5. 启用文件缓存

针对静态文件的缓存

http {
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors off;
    # 其他配置...
}

6. WebP 图片支持

启用 WebP 图片以提高加载速度

http {
    map $http_accept $webp_suffix {
        default "";
        "~*webp" ".webp";
    }

    server {
        location ~ \.(jpe?g|png)$ {
            add_header Vary Accept;
            try_files $uri$webp_suffix $uri =404;
        }
    }
}

7. 使用防火墙规则

配置 UFW 防火墙规则

sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable

通过以上配置,你可以提高 Nginx 服务器的安全性和性能。请根据实际需求和环境进行适当的调整,并确保在应用配置之前进行备份和测试。