Windows 环境下 Nginx 的安装与高级配置指南

第一章:Windows 平台 Nginx 概述

1.1 Windows 版 Nginx 特点

Nginx 在 Windows 平台上的实现与 Unix/Linux 版本相比有以下特点:

特性 Windows 版 Linux 版
性能 略低(约 Linux 的 70%) 原生高性能
进程模型 单工作进程 多工作进程
信号处理 有限支持 完整支持
配置文件热重载 支持 支持
文件描述符限制 受 Windows 限制 可调优
社区支持 较少 丰富

1.2 适用场景分析

Windows 版 Nginx 适合以下场景:

  • 开发测试环境
  • 小型生产环境(低流量)
  • 本地 API 网关
  • 前端开发服务器
  • 企业内部应用代理

第二章:Nginx 安装与配置

2.1 下载与安装

# 1. 创建安装目录
mkdir C:\nginx
cd C:\nginx

# 2. 下载最新稳定版(PowerShell)
Invoke-WebRequest -Uri "https://nginx.org/download/nginx-1.23.3.zip" -OutFile "nginx-1.23.3.zip"

# 3. 解压文件
Expand-Archive -Path .\nginx-1.23.3.zip -DestinationPath .

# 4. 重命名目录
Rename-Item .\nginx-1.23.3 .\nginx

# 5. 测试启动
cd .\nginx
start nginx

2.2 目录结构说明

C:\nginx\
├── conf/            # 配置文件目录
│   ├── nginx.conf   # 主配置文件
│   └── ...          # 其他配置
├── html/            # 默认网站目录
│   ├── 50x.html     # 错误页面
│   └── index.html   # 首页
├── logs/            # 日志目录
├── nginx.exe        # 主程序
└── temp/            # 临时文件

2.3 注册为系统服务(可选)

创建 nginx-service.ps1 脚本:

$serviceName = "Nginx"
$nginxPath = "C:\nginx\nginx.exe"

# 检查是否已存在
if (Get-Service $serviceName -ErrorAction SilentlyContinue) {
   
    Write-Host "服务已存在"
    exit
}

# 创建服务
New-Service -Name $serviceName `
            -BinaryPathName "`"$nginxPath`" -g `"daemon off;`"" `
            -DisplayName "Nginx HTTP Server" `
            -StartupType Automatic `
            -Description "Nginx HTTP and Reverse Proxy Server"

# 启动服务
Start-Service -Name $serviceName
Write-Host "Nginx 服务安装完成"

第三章:基础配置与优化

3.1 主配置文件优化 (conf/nginx.conf)

worker_processes  1;  # Windows 只能使用单工作进程

events {
    worker_connections  1024;  # 最大连接数
    use select;        # Windows 使用 select 事件模型
}

http {
    include       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  logs/access.log  main buffer=32k flush=5s;
    error_log   logs/error.log warn;

    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;

    # 文件缓存
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # Gzip 压缩
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 4;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    include conf.d/*.conf;
}

3.2 虚拟主机配置示例

创建 conf/conf.d/example.conf

server {
    listen       80;
    server_name  localhost example.com;

    # 字符集
    charset utf-8;

    # 静态文件服务
    location / {
        root   html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    # API 代理
    location /api/ {
        proxy_pass http://localhost:3000/;
        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_connect_timeout 5s;
        proxy_read_timeout 30s;
        proxy_send_timeout 15s;
    }

    # 错误页面
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

第四章:性能优化策略

4.1 Windows 特有优化参数

# 在 events 块中添加
events {
    accept_mutex off;       # Windows 不需要互斥锁
    worker_connections 2048; # 根据内存调整
}

# 在 http 块中添加
http {
    # 提高 Windows 下的性能
    sendfile_max_chunk 512k;
    directio 4m;
    
    # 输出缓冲
    output_buffers 4 32k;
    postpone_output 1460;
}

4.2 不同配置性能对比

使用 wrk 工具测试本地性能(i7-10700/16GB RAM):

优化项 请求/秒 (RPS) 平均延迟(ms) 内存占用(MB) CPU 使用率
默认配置 8,456 11.8 120 45%
基础优化 11,234 (+33%) 8.9 150 60%
高级优化 13,789 (+63%) 7.2 180 75%
关闭日志 15,342 (+81%) 6.5 160 80%

4.3 系统参数调整

# 调整 TCP 参数(管理员权限运行)
netsh int tcp set global autotuninglevel=restricted
netsh int tcp set global rss=enabled
netsh int tcp set global chimney=automatic

# 增加最大连接数
reg add HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters /v MaxConnectionsPerServer /t REG_DWORD /d 10000 /f
reg add HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters /v MaxConcurrentConnections /t REG_DWORD /d 10000 /f

# 重启生效
Restart-Computer -Force

第五章:安全配置

5.1 SSL/TLS 配置

server {
    listen       443 ssl;
    server_name  example.com;

    ssl_certificate      cert/example.com.crt;
    ssl_certificate_key  cert/example.com.key;
    
    # 安全协议配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    
    # 安全头部
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    
    # 其他配置...
}

5.2 生成自签名证书

# 1. 创建证书目录
mkdir C:\nginx\cert
cd C:\nginx\cert

# 2. 生成私钥
openssl genrsa -out example.com.key 2048

# 3. 生成 CSR
openssl req -new -key example.com.key -out example.com.csr `
    -subj "/C=CN/ST=Beijing/L=Beijing/O=Example Inc./OU=Web Security/CN=example.com"

# 4. 生成自签名证书
openssl x509 -req -days 365 -in example.com.csr -signkey example.com.key -out example.com.crt

# 5. 将证书添加到受信任根证书
Import-Certificate -FilePath .\example.com.crt -CertStoreLocation Cert:\LocalMachine\Root

第六章:高级功能配置

6.1 负载均衡配置

upstream backend {
    least_conn;  # 最少连接算法
    
    server 127.0.0.1:8001 weight=3;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003 backup;
    
    keepalive 16;  # 保持连接数
}

server {
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        
        # 其他代理设置...
    }
}

6.2 缓存配置

proxy_cache_path C:/nginx/cache levels=1:2 keys_zone=my_cache:10m 
                inactive=60m use_temp_path=off max_size=1g;

server {
    location / {
        proxy_cache my_cache;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        
        # 缓存状态头
        add_header X-Proxy-Cache $upstream_cache_status;
        
        proxy_pass http://backend;
    }
}

第七章:监控与维护

7.1 状态监控配置

server {
    listen 127.0.0.1:8080;
    
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
    
    location /server-info {
        return 200 "Server: $hostname\nNginx: $nginx_version\nUptime: $uptime";
    }
}

7.2 日志分析脚本

创建 analyze_logs.ps1

# 分析访问日志
$logFile = "C:\nginx\logs\access.log"

# 1. 统计状态码
Write-Host "`nHTTP 状态码统计:"
Select-String -Path $logFile -Pattern 'HTTP/1.\" (\d{3})' | 
    ForEach-Object {
    $_.Matches.<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦幻南瓜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值