一、Nginx环境搭建与基础配置
1.1 系统环境准备
在Linux系统上部署Nginx前,需完成基础依赖安装。推荐使用Ubuntu/Debian系列系统,执行以下命令更新软件包索引并安装编译工具链:
sudo apt update && sudo apt upgrade -ysudo apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
其中libpcre3-dev提供正则表达式支持,zlib1g-dev用于GZIP压缩,libssl-dev是HTTPS模块必需的依赖。对于CentOS/RHEL系统,需替换为yum groupinstall "Development Tools"并单独安装对应开发包。
1.2 源码编译安装
采用源码编译方式可灵活控制功能模块,具体步骤如下:
-
创建专用用户:遵循最小权限原则,创建无登录权限的nginx用户
sudo groupadd -r nginxsudo useradd -r -g nginx -s /sbin/nologin nginx
-
下载解压源码:从官方托管仓库获取稳定版本(示例使用1.24.0版本)
cd /tmpwget http://nginx.org/download/nginx-1.24.0.tar.gztar zxvf nginx-*.tar.gzcd nginx-1.24.0
-
配置编译参数:关键参数说明如下:
./configure \--prefix=/usr/local/nginx \ # 安装目录--user=nginx \ # 运行用户--group=nginx \ # 运行组--with-http_ssl_module \ # 启用HTTPS--with-http_v2_module \ # 支持HTTP/2--with-http_realip_module \ # 获取真实客户端IP--with-http_stub_status_module \ # 监控状态页--with-stream \ # TCP/UDP代理支持--with-threads # 启用线程池
-
编译安装:使用多核编译加速过程
make -j$(nproc) && sudo make install
-
注册系统服务:创建systemd服务文件实现开机自启
```ini/etc/systemd/system/nginx.service
[Unit]
Description=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=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
执行以下命令启用服务:```bashsudo systemctl daemon-reloadsudo systemctl enable --now nginx
二、静态资源服务配置
2.1 网站目录规划
遵循安全规范创建目录结构:
sudo mkdir -p /var/www/static-site/{html,logs,conf}sudo chown -R nginx:nginx /var/www/static-sitesudo chmod -R 750 /var/www/static-site
其中conf目录可用于存放站点专属配置,实现配置与代码分离。
2.2 基础配置示例
创建站点配置文件/var/www/static-site/conf/default.conf:
server {listen 80;server_name example.com;root /var/www/static-site/html;index index.html index.htm;access_log /var/www/static-site/logs/access.log main;error_log /var/www/static-site/logs/error.log warn;location / {try_files $uri $uri/ =404;expires 7d; # 静态资源缓存add_header Cache-Control "public";}# 禁止访问隐藏文件location ~ /\. {deny all;access_log off;log_not_found off;}}
在主配置文件nginx.conf的http块中引入:
http {include /var/www/static-site/conf/*.conf;# 其他全局配置...}
2.3 性能优化技巧
-
GZIP压缩:在http块添加
gzip on;gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;gzip_min_length 1k;gzip_comp_level 6;
-
静态资源缓存:针对不同文件类型设置差异化缓存策略
```nginx
location ~* .(jpg|jpeg|png|gif|ico)$ {
expires 30d;
access_log off;
}
location ~* .(css|js)$ {
expires 7d;
add_header Cache-Control “public, no-transform”;
}
# 三、负载均衡集群部署## 3.1 反向代理基础配置上游服务器组:```nginxupstream backend_servers {server 192.168.1.100:8080 weight=5;server 192.168.1.101:8080;server 192.168.1.102:8080 backup;keepalive 32; # 保持长连接数量}
参数说明:
weight:权重分配,默认1backup:备用服务器,主服务器不可用时启用keepalive:减少TCP连接建立开销
3.2 负载均衡策略
- 轮询(默认):请求按顺序分配到各服务器
-
IP哈希:相同客户端IP固定分配到同一服务器
upstream backend_servers {ip_hash;server 192.168.1.100;server 192.168.1.101;}
-
最少连接:优先分配给活跃连接最少的服务器
upstream backend_servers {least_conn;server 192.168.1.100;server 192.168.1.101;}
3.3 健康检查机制
通过max_fails和fail_timeout实现故障自动隔离:
upstream backend_servers {server 192.168.1.100 max_fails=3 fail_timeout=30s;server 192.168.1.101 max_fails=3 fail_timeout=30s;}
当服务器连续3次失败(默认502/504状态码),将在30秒内不再分配新请求。
四、生产环境最佳实践
4.1 安全加固
-
隐藏版本信息:在nginx.conf中添加
server_tokens off;
-
限制访问速率:防止CC攻击
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;server {location / {limit_req zone=one burst=5;}}
4.2 监控运维
-
状态监控页:启用stub_status模块
location /nginx_status {stub_status on;allow 192.168.1.0/24;deny all;}
-
日志切割:创建日志切割脚本
/etc/logrotate.d/nginx/usr/local/nginx/logs/*.log {dailymissingokrotate 14compressdelaycompressnotifemptycreate 0640 nginx admsharedscriptspostrotateif [ -f /usr/local/nginx/logs/nginx.pid ]; thenkill -USR1 `cat /usr/local/nginx/logs/nginx.pid`fiendscript}
4.3 高可用方案
采用Keepalived实现VIP漂移:
-
安装Keepalived
sudo apt install keepalived
-
配置检测脚本
/etc/keepalived/check_nginx.sh#!/bin/bashif [ ! -s /usr/local/nginx/logs/nginx.pid ]; thensystemctl start nginxsleep 3if [ ! -s /usr/local/nginx/logs/nginx.pid ]; thenexit 1fifiexit 0
-
主节点配置示例
```ini
vrrp_script chk_nginx {
script “/etc/keepalived/check_nginx.sh”
interval 2
weight -20
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.200/24
}
track_script {
chk_nginx
}
}
```
通过以上配置,开发者可构建从基础网站服务到企业级高可用架构的完整Nginx解决方案。实际部署时需根据业务规模调整线程池大小、连接数等参数,建议通过压力测试工具验证配置有效性。