Nginx 服务器部署与优化全攻略

一、Nginx基础部署与环境准备

1.1 安装方式选择

主流Linux发行版均提供Nginx软件包,推荐采用系统包管理器安装以获得最佳兼容性。以CentOS为例:

  1. # 使用yum安装(推荐)
  2. sudo yum install epel-release # 启用EPEL仓库
  3. sudo yum install nginx
  4. # 编译安装(适合定制需求)
  5. wget http://nginx.org/download/nginx-1.25.3.tar.gz
  6. tar -zxvf nginx-1.25.3.tar.gz
  7. cd nginx-1.25.3
  8. ./configure --with-http_ssl_module --with-stream
  9. make && make install

编译安装时建议添加--with-http_ssl_module(SSL支持)和--with-stream(TCP/UDP代理)等常用模块。

1.2 服务管理基础

安装完成后需掌握基础服务控制命令:

  1. # 系统服务方式(yum安装)
  2. systemctl start nginx # 启动服务
  3. systemctl enable nginx # 设置开机自启
  4. systemctl status nginx # 查看运行状态
  5. # 编译安装需手动管理
  6. /usr/local/nginx/sbin/nginx # 启动
  7. /usr/local/nginx/sbin/nginx -s stop # 停止
  8. /usr/local/nginx/sbin/nginx -s reload # 热重载配置

建议将编译安装的二进制路径加入PATH环境变量,或创建systemd服务单元文件实现标准化管理。

二、安全加固核心方案

2.1 版本信息隐藏

攻击者常通过版本号探测已知漏洞,可通过以下配置隐藏:

  1. http {
  2. server_tokens off; # 关闭响应头中的版本号
  3. # 对于编译安装版本,需同时修改源码
  4. # 在nginx.h中修改#define NGINX_VERSION和NGINX_VER
  5. }

测试验证:

  1. curl -I http://localhost | grep Server
  2. # 应返回 "Server: nginx" 而非具体版本

2.2 HTTPS强制跳转

明文HTTP存在中间人攻击风险,推荐全站HTTPS化:

  1. server {
  2. listen 80;
  3. server_name example.com;
  4. return 301 https://$server_name$request_uri;
  5. }
  6. server {
  7. listen 443 ssl;
  8. ssl_certificate /path/to/cert.pem;
  9. ssl_certificate_key /path/to/key.pem;
  10. # 推荐配置:
  11. ssl_protocols TLSv1.2 TLSv1.3;
  12. ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
  13. }

使用ssllabs.com等工具检测SSL配置安全性,建议启用HSTS头增强防护:

  1. add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

2.3 访问控制增强

通过IP白名单限制管理接口访问:

  1. server {
  2. listen 8080;
  3. allow 192.168.1.100; # 允许特定IP
  4. deny all; # 拒绝其他IP
  5. location / {
  6. proxy_pass http://backend;
  7. }
  8. }

对于动态内容,建议结合防火墙规则实现多层防护。

三、性能优化实践方案

3.1 静态资源加速

合理配置缓存策略可显著降低后端压力:

  1. location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
  2. expires 30d; # 缓存30天
  3. access_log off; # 关闭日志记录
  4. add_header Cache-Control "public";
  5. }

对于大文件传输,启用sendfiletcp_nopush

  1. http {
  2. sendfile on;
  3. tcp_nopush on;
  4. # 对于高并发场景,调整系统参数
  5. # sysctl -w net.ipv4.tcp_max_syn_backlog=4096
  6. }

3.2 动态请求优化

通过连接池和缓冲设置提升反向代理性能:

  1. upstream backend {
  2. server 127.0.0.1:8080;
  3. keepalive 32; # 保持长连接数
  4. }
  5. server {
  6. location / {
  7. proxy_pass http://backend;
  8. proxy_http_version 1.1;
  9. proxy_set_header Connection "";
  10. proxy_buffering on;
  11. proxy_buffer_size 4k;
  12. proxy_buffers 8 16k;
  13. }
  14. }

建议对API接口启用Gzip压缩:

  1. gzip on;
  2. gzip_types application/json text/css application/javascript;
  3. gzip_min_length 1k;
  4. gzip_comp_level 6;

3.3 负载均衡策略

根据业务特点选择合适算法:

  1. upstream backend {
  2. # 轮询(默认)
  3. server 10.0.0.1:8080;
  4. server 10.0.0.2:8080;
  5. # 加权轮询(按权重分配)
  6. # server 10.0.0.1:8080 weight=3;
  7. # server 10.0.0.2:8080 weight=1;
  8. # IP哈希(保证同一客户端固定后端)
  9. # hash $remote_addr;
  10. # 最少连接(适合长连接场景)
  11. # least_conn;
  12. }

建议配置健康检查:

  1. server {
  2. location / {
  3. proxy_pass http://backend;
  4. proxy_next_upstream error timeout http_502;
  5. }
  6. }

四、监控与运维体系

4.1 日志管理方案

配置分离访问日志和错误日志:

  1. http {
  2. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  3. '$status $body_bytes_sent "$http_referer" '
  4. '"$http_user_agent" "$http_x_forwarded_for"';
  5. access_log /var/log/nginx/access.log main;
  6. error_log /var/log/nginx/error.log warn;
  7. }

建议使用logrotate进行日志轮转,或对接日志分析系统。

4.2 进程监控

通过nginx -t检测配置语法:

  1. /usr/local/nginx/sbin/nginx -t
  2. # 输出 "syntax is ok" 和 "test is successful" 表示正常

监控工作进程状态:

  1. ps aux | grep nginx | grep -v grep
  2. # 正常应显示1个master进程和多个worker进程

4.3 性能基准测试

使用wrk工具进行压力测试:

  1. wrk -t4 -c100 -d30s http://example.com/
  2. # 输出QPS、延迟等关键指标

根据测试结果调整worker_processesworker_connections参数:

  1. events {
  2. worker_connections 10240; # 每个worker最大连接数
  3. }
  4. worker_processes auto; # 通常设置为CPU核心数

五、高级功能扩展

5.1 WebSocket支持

  1. map $http_upgrade $connection_upgrade {
  2. default upgrade;
  3. '' close;
  4. }
  5. server {
  6. location /ws {
  7. proxy_pass http://backend;
  8. proxy_http_version 1.1;
  9. proxy_set_header Upgrade $http_upgrade;
  10. proxy_set_header Connection $connection_upgrade;
  11. }
  12. }

5.2 HTTP/2加速

  1. server {
  2. listen 443 ssl http2;
  3. # 必须启用SSL才能使用HTTP/2
  4. ssl_certificate /path/to/cert.pem;
  5. ssl_certificate_key /path/to/key.pem;
  6. }

5.3 动态模块加载

编译时添加--with-compat支持动态模块:

  1. ./configure --with-compat --add-module=/path/to/module
  2. make modules
  3. # 动态加载模块
  4. load_module modules/ngx_http_example_module.so;

通过系统化的配置优化,Nginx可承载百万级并发请求,成为企业级Web架构的核心组件。建议定期审查配置参数,结合监控数据持续调优,构建适应业务发展的高弹性服务架构。