Nginx作为当前最主流的高性能Web服务器之一,其市场份额已超过Apache位居全球第一。根据W3Techs最新统计,全球活跃网站中约有34%采用Nginx作为服务器。这个2004年由俄罗斯工程师Igor Sysoev开发的开源项目,凭借其事件驱动的异步架构,在处理高并发请求时内存消耗极低,单机即可轻松支撑数万并发连接。
在开始安装前需要确认系统环境。我推荐使用Linux发行版作为生产环境,本文以CentOS 7为例演示完整流程。Windows环境下虽然也有官方编译好的二进制包,但性能损失约15-20%,且稳定性不如Linux版本。准备阶段需要确保:
重要提示:生产环境强烈建议禁用root直接登录,通过普通用户+sudo方式操作更安全。可通过
adduser deploy创建专用部署账户,然后usermod -aG wheel deploy加入管理员组。
首先安装编译工具链和基础依赖库:
bash复制sudo yum groupinstall "Development Tools"
sudo yum install -y pcre-devel zlib-devel openssl-devel
这里特别说明各依赖包的作用:
到官网(nginx.org)获取稳定版源码,当前最新为1.25.3:
bash复制wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
编译配置建议使用以下参数组合:
bash复制./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-threads \
--with-file-aio
关键模块说明:
执行编译安装:
bash复制make -j$(nproc) && sudo make install
-j参数表示使用所有CPU核心并行编译,可大幅缩短编译时间。
创建专用系统账户并设置目录权限:
bash复制sudo useradd -r -s /sbin/nologin nginx
sudo chown -R nginx:nginx /usr/local/nginx
创建systemd服务文件/lib/systemd/system/nginx.service:
ini复制[Unit]
Description=nginx - high performance web server
After=network.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
User=nginx
Group=nginx
[Install]
WantedBy=multi-user.target
启用服务:
bash复制sudo systemctl daemon-reload
sudo systemctl enable nginx
sudo systemctl start nginx
Nginx配置文件采用树状结构,主要包含:
code复制/usr/local/nginx/conf/
├── nginx.conf # 主配置文件
├── mime.types # MIME类型映射
└── conf.d/ # 子配置目录
主配置文件采用分段式结构:
nginx复制main # 全局配置
events { # 连接处理参数
worker_connections 1024;
}
http { # HTTP服务配置
server { # 虚拟主机配置
location / { # URL路由配置
root /var/www/html;
}
}
}
nginx复制user nginx; # 运行用户
worker_processes auto; # 自动匹配CPU核心数
error_log /var/log/nginx/error.log warn; # 错误日志路径及级别
pid /run/nginx.pid; # PID文件位置
nginx复制events {
worker_connections 2048; # 每个worker最大连接数
multi_accept on; # 同时接受所有新连接
use epoll; # Linux高性能事件模型
}
nginx复制http {
include mime.types; # 引入MIME类型定义
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
sendfile on; # 零拷贝传输
tcp_nopush on; # 优化数据包发送
keepalive_timeout 65; # 长连接超时
gzip on; # 启用压缩
gzip_types text/plain text/css application/json;
include conf.d/*.conf; # 加载子配置文件
}
创建conf.d/example.com.conf:
nginx复制server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
include fastcgi_params;
}
location ~ /\.ht {
deny all; # 禁止访问.htaccess文件
}
}
编辑/etc/sysctl.conf:
conf复制net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
fs.file-max = 2097152
执行sysctl -p生效。
nginx复制worker_rlimit_nofile 65535; # 文件描述符限制
http {
client_max_body_size 20m; # 上传文件大小限制
client_body_buffer_size 128k;
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
}
nginx复制server_tokens off; # 隐藏Nginx版本号
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
location = /wp-login.php {
limit_req zone=one burst=3 nodelay;
include fastcgi_params;
}
bash复制# 测试配置文件
nginx -t
# 热重载配置
nginx -s reload
# 查看运行状态
systemctl status nginx
# 查看进程树
ps auxf | grep nginx
分析访问日志TOP IP:
bash复制awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -20
统计HTTP状态码:
bash复制awk '{print $9}' access.log | sort | uniq -c | sort -rn
tail -f /var/log/nginx/error.logbash复制sudo netstat -tulnp | grep :80
sudo lsof -i :80
bash复制top -p $(pgrep -d',' nginx)
strace -p <worker_pid> -c
nginx复制upstream backend {
least_conn; # 最小连接算法
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080;
server 192.168.1.12:8080 backup;
}
server {
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
}
}
nginx复制proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_use_stale error timeout updating;
}
}
创建/etc/logrotate.d/nginx:
conf复制/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 nginx adm
sharedscripts
postrotate
[ -f /run/nginx.pid ] && kill -USR1 `cat /run/nginx.pid`
endscript
}