1. 首页 > IT综合教程 > 正文

252. Nginx Web服务器培训

一、Nginx概述

Nginx是高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器。以高并发、低内存消耗、模块化设计著称。

学习交流加群风哥QQ113257174

1.1 Nginx核心特性

  • 高并发:支持数万并发连接
  • 反向代理:支持HTTP、HTTPS、FastCGI等协议
  • 负载均衡:支持多种负载均衡算法
  • 静态资源服务:高效的静态文件处理能力

1.2 Nginx架构

Nginx进程模型:
┌─────────────────────────────────────────┐
│            Master Process               │
│  - 读取配置文件                          │
│  - 管理Worker进程                        │
└─────────────────────────────────────────┘
         │           │           │
         ▼           ▼           ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│   Worker    │ │   Worker    │ │   Worker    │
│  Process 1  │ │  Process 2  │ │  Process N  │
└─────────────┘ └─────────────┘ └─────────────┘
         │           │           │
         ▼           ▼           ▼
┌─────────────────────────────────────────┐
│            Cache Manager                │
│            Cache Loader                 │
└─────────────────────────────────────────┘

二、Nginx安装部署

2.1 源码编译安装

# 安装依赖
yum install -y gcc pcre-devel zlib-devel openssl-devel

# 下载Nginx
wget https://nginx.org/download/nginx-1.24.0.tar.gz
tar -xzf nginx-1.24.0.tar.gz
cd nginx-1.24.0

# 配置编译选项
./configure \
    --prefix=/usr/local/nginx \
    --user=nginx \
    --group=nginx \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_gzip_static_module \
    --with-http_stub_status_module \
    --with-stream \
    --with-stream_ssl_module

# 编译安装
make && make install

# 创建nginx用户
useradd -r -s /sbin/nologin nginx

# 创建systemd服务
cat > /etc/systemd/system/nginx.service << 'EOF'
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

# 启动服务
systemctl daemon-reload
systemctl start nginx
systemctl enable nginx
# 输出示例
Checking configuration...
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
Starting nginx: [ OK ]

2.2 YUM安装

# 添加Nginx官方仓库
cat > /etc/yum.repos.d/nginx.repo << 'EOF'
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
EOF

# 安装Nginx
yum install -y nginx

# 启动服务
systemctl start nginx
systemctl enable nginx

# 查看版本
nginx -v
nginx -V

三、Nginx配置详解

3.1 主配置文件结构

# nginx.conf
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

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

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    
    access_log /var/log/nginx/access.log main;
    
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript;
    
    include /etc/nginx/conf.d/*.conf;
}

3.2 虚拟主机配置

# /etc/nginx/conf.d/example.conf
server {
    listen 80;
    server_name www.fgedu.net.cn fgedu.net.cn;
    root /var/www/example;
    index index.html index.htm;
    
    access_log /var/log/nginx/example.access.log main;
    error_log /var/log/nginx/example.error.log;
    
    location / {
        try_files $uri $uri/ =404;
    }
    
    location /images/ {
        alias /var/www/images/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
    location ~ /\. {
        deny all;
    }
    
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

四、反向代理配置

4.1 基本反向代理

# 反向代理配置
upstream backend {
    server 192.168.1.101:8080 weight=3;
    server 192.168.1.102:8080 weight=2;
    server 192.168.1.103:8080 backup;
    keepalive 32;
}

server {
    listen 80;
    server_name api.fgedu.net.cn;
    
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Connection "";
        
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 16k;
        proxy_busy_buffers_size 24k;
    }
}

4.2 负载均衡策略

# 轮询(默认)
upstream backend {
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

# 加权轮询
upstream backend {
    server 192.168.1.101:8080 weight=5;
    server 192.168.1.102:8080 weight=3;
    server 192.168.1.103:8080 weight=2;
}

# IP Hash
upstream backend {
    ip_hash;
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

# 最少连接
upstream backend {
    least_conn;
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

# 一致性Hash
upstream backend {
    hash $request_uri consistent;
    server 192.168.1.101:8080;
    server 192.168.1.102:8080;
}

# 健康检查(商业版)
upstream backend {
    server 192.168.1.101:8080 max_fails=3 fail_timeout=30s;
    server 192.168.1.102:8080 max_fails=3 fail_timeout=30s;
}

五、SSL/TLS配置

5.1 HTTPS配置

# SSL证书配置
server {
    listen 443 ssl http2;
    server_name www.fgedu.net.cn;
    
    ssl_certificate /etc/nginx/ssl/fgedu.net.cn.crt;
    ssl_certificate_key /etc/nginx/ssl/fgedu.net.cn.key;
    
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    location / {
        proxy_pass http://backend;
    }
}

# HTTP重定向HTTPS
server {
    listen 80;
    server_name www.fgedu.net.cn;
    return 301 https://$server_name$request_uri;
}

5.2 双向SSL认证

server {
    listen 443 ssl;
    server_name secure.fgedu.net.cn;
    
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;
    
    ssl_client_certificate /etc/nginx/ssl/ca.crt;
    ssl_verify_client on;
    ssl_verify_depth 2;
    
    location / {
        proxy_pass http://backend;
        proxy_set_header X-SSL-Client-CN $ssl_client_s_dn_cn;
        proxy_set_header X-SSL-Client-Serial $ssl_client_serial;
    }
}

六、缓存配置

6.1 代理缓存

# 缓存配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:100m
                 max_size=10g inactive=60m use_temp_path=off;

server {
    listen 80;
    server_name api.fgedu.net.cn;
    
    location / {
        proxy_pass http://backend;
        proxy_cache api_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_key $scheme$request_method$host$request_uri;
        proxy_cache_use_stale error timeout updating http_500;
        
        add_header X-Cache-Status $upstream_cache_status;
    }
    
    location ~ /purge(/.*) {
        allow 192.168.1.0/24;
        deny all;
        proxy_cache_purge api_cache $scheme$request_method$host$1;
    }
}

6.2 静态资源缓存

server {
    listen 80;
    server_name static.fgedu.net.cn;
    root /var/www/static;
    
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        add_header Last-Modified "";
        etag off;
        
        open_file_cache max=10000 inactive=30s;
        open_file_cache_valid 60s;
        open_file_cache_min_uses 2;
        open_file_cache_errors on;
    }
    
    location ~* \.(html)$ {
        expires 1h;
        add_header Cache-Control "public, must-revalidate";
    }
}

七、限流与安全

7.1 请求限流

# 限流配置
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

server {
    listen 80;
    server_name api.fgedu.net.cn;
    
    location /api/ {
        limit_req zone=api_limit burst=20 nodelay;
        limit_req_status 429;
        
        limit_conn conn_limit 10;
        limit_conn_status 429;
        
        proxy_pass http://backend;
    }
}

# 基于IP的白名单
geo $limit {
    default 1;
    192.168.1.0/24 0;
    10.0.0.0/8 0;
}

map $limit $limit_key {
    0 "";
    1 $binary_remote_addr;
}

limit_req_zone $limit_key zone=api_limit:10m rate=10r/s;

7.2 安全配置

server {
    listen 80;
    server_name fgedu.net.cn;
    
    # 隐藏版本号
    server_tokens off;
    
    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Content-Security-Policy "default-src 'self'" always;
    
    # 防止目录遍历
    location ~ /\. {
        deny all;
    }
    
    # 限制请求方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }
    
    # 防止SQL注入
    if ($query_string ~* "union.*select.*\(") {
        return 403;
    }
    if ($query_string ~* "concat.*\(") {
        return 403;
    }
    
    # 防止文件上传攻击
    location ~* /uploads/.*\.php$ {
        deny all;
    }
    
    # IP访问控制
    location /admin/ {
        allow 192.168.1.0/24;
        deny all;
        proxy_pass http://backend;
    }
}

八、日志管理

8.1 日志格式配置

# 自定义日志格式
log_format json_combined escape=json
    '{'
        '"time_local":"$time_local",'
        '"remote_addr":"$remote_addr",'
        '"remote_user":"$remote_user",'
        '"request":"$request",'
        '"status":"$status",'
        '"body_bytes_sent":"$body_bytes_sent",'
        '"request_time":"$request_time",'
        '"http_referrer":"$http_referer",'
        '"http_user_agent":"$http_user_agent",'
        '"http_x_forwarded_for":"$http_x_forwarded_for",'
        '"upstream_addr":"$upstream_addr",'
        '"upstream_response_time":"$upstream_response_time"'
    '}';

server {
    access_log /var/log/nginx/access.log json_combined;
    
    # 条件日志
    location /health {
        access_log off;
        return 200 "OK";
    }
    
    # 错误日志级别
    error_log /var/log/nginx/error.log warn;
}

8.2 日志轮转

# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 nginx adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

# 手动执行日志轮转
logrotate -f /etc/logrotate.d/nginx

九、性能优化

9.1 内核参数优化

# /etc/sysctl.conf
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_tw_buckets = 65535
net.ipv4.ip_local_port_range = 1024 65535

# 应用配置
sysctl -p

9.2 Nginx性能优化

# nginx.conf优化配置
user nginx;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;

events {
    use epoll;
    worker_connections 65535;
    multi_accept on;
    accept_mutex off;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    
    keepalive_timeout 65;
    keepalive_requests 1000;
    
    open_file_cache max=65535 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
    
    reset_timedout_connection on;
    client_body_timeout 10;
    send_timeout 2;
}

十、运维命令

10.1 常用管理命令

# 测试配置
nginx -t
nginx -t -c /etc/nginx/nginx.conf

# 启动/停止/重启
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx

# 信号控制
nginx -s stop     # 快速停止
nginx -s quit     # 优雅停止
nginx -s reload   # 重新加载配置
nginx -s reopen   # 重新打开日志

# 查看进程
ps -ef | grep nginx

# 查看连接状态
ss -tlnp | grep nginx
netstat -tlnp | grep nginx

# 查看版本和编译参数
nginx -v
nginx -V

10.2 状态监控

# 启用stub_status
server {
    listen 80;
    server_name status.fgedu.net.cn;
    
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 192.168.1.0/24;
        deny all;
    }
}

# 访问状态页面
curl http://status.fgedu.net.cn/nginx_status
# 输出示例
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106

十一、最佳实践

11.1 配置建议

配置项 建议值 说明
worker_processes auto 自动匹配CPU核心数
worker_connections 65535 最大连接数
keepalive_timeout 65 保持连接时间
gzip on 启用压缩
注意事项:

  • 生产环境必须启用HTTPS
  • 配置合理的安全头
  • 定期备份配置文件
  • 监控日志和性能指标

十二、总结

Nginx是高性能Web服务器和反向代理的重要工具。通过本培训文档,您应该掌握了:

  • Nginx的安装部署方法
  • 虚拟主机和反向代理配置
  • 负载均衡策略的选择
  • SSL/TLS安全配置
  • 缓存和限流配置
  • 性能优化和运维管理
IT运维培训文档系列 | 第252篇 | Nginx Web服务器培训

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息