1. Nginx概述与环境规划
Nginx是一款高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。由俄罗斯程序员Igor Sysoev开发,以高并发、低内存占用著称。更多学习教程www.fgedu.net.cn
1.1 Nginx版本说明
Nginx目前主要版本为1.26,本教程以Nginx 1.26为例进行详细讲解。
$ nginx -v
nginx version: nginx/1.26.0
# 查看编译参数
$ nginx -V
nginx version: nginx/1.26.0
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-20) (GCC)
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: –prefix=/etc/nginx –sbin-path=/usr/sbin/nginx –modules-path=/usr/lib64/nginx/modules –conf-path=/etc/nginx/nginx.conf –error-log-path=/var/log/nginx/error.log –http-log-path=/var/log/nginx/access.log –pid-path=/var/run/nginx.pid –lock-path=/var/run/nginx.lock –with-http_ssl_module –with-http_v2_module –with-http_realip_module –with-http_gzip_static_module
# 检查配置语法
$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
1.2 环境规划
本次安装环境规划如下:
IP地址:192.168.1.51
HTTP端口:80
HTTPS端口:443
安装目录:/etc/nginx
日志目录:/var/log/nginx
配置目录:/etc/nginx/conf.d
网站根目录:/data/nginx/html
Nginx版本:1.26.0
OpenSSL版本:3.0.7
1.3 Nginx核心特性
1. 高并发:支持数万并发连接
2. 低内存:每连接内存占用小
3. 反向代理:支持HTTP/HTTPS/FASTCGI等
4. 负载均衡:支持多种负载均衡算法
5. 虚拟主机:支持基于IP、端口、域名的虚拟主机
6. SSL/TLS:支持HTTPS和SSL证书
7. 缓存:支持代理缓存和FastCGI缓存
8. 模块化:丰富的第三方模块支持
2. 硬件环境要求与检查
在安装Nginx之前,需要对服务器硬件环境进行全面检查。学习交流加群风哥微信: itpux-com
2.1 最低硬件要求
CPU:1核心
内存:512MB
磁盘:5GB
推荐配置(生产环境):
CPU:4核心以上
内存:4GB以上
磁盘:50GB以上
高并发配置:
CPU:8核心以上
内存:16GB以上
磁盘:100GB以上(SSD)
2.2 系统环境检查
# cat /etc/redhat-release
Red Hat Enterprise Linux release 8.8 (Ootpa)
# 检查内核版本
# uname -r
4.18.0-477.27.1.el8_8.x86_64
# 检查内存信息
# free -h
total used free shared buff/cache available
Mem: 15Gi 1.0Gi 13Gi 256Mi 1.0Gi 14Gi
Swap: 7Gi 0B 7Gi
# 检查磁盘空间
# df -h
文件系统 容量 已用 可用 已用% 挂载点
/dev/mapper/vg_system-lv_root 100G 5.0G 95G 5% /
/dev/mapper/vg_data-lv_data 500G 50G 450G 10% /data
2.3 依赖包检查
# rpm -qa | grep -E “gcc|pcre|zlib|openssl”
gcc-8.5.0-20.el8.x86_64
pcre-devel-8.45-1.el8.x86_64
zlib-devel-1.2.11-25.el8.x86_64
openssl-devel-3.0.7-24.el8.x86_64
# 安装依赖包
# yum install -y gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
# 输出示例:
Last metadata expiration check: 0:00:00 ago on Sat Apr 4 10:00:00 2026.
Dependencies resolved.
Complete!
3. Nginx安装步骤
本节详细介绍Nginx 1.26的安装过程。学习交流加群风哥QQ113257174
3.1 创建用户和目录
# groupadd -g 80 nginx
# useradd -u 80 -g nginx -s /sbin/nologin -M nginx
# 创建目录
# mkdir -p /etc/nginx
# mkdir -p /var/log/nginx
# mkdir -p /var/cache/nginx/{client_temp,proxy_temp,fastcgi_temp,uwsgi_temp,scgi_temp}
# mkdir -p /data/nginx/{html,ssl,conf.d}
# 设置目录权限
# chown -R nginx:nginx /var/log/nginx
# chown -R nginx:nginx /var/cache/nginx
# chown -R nginx:nginx /data/nginx
3.2 下载并编译安装
# cd /usr/local/src
# wget http://nginx.org/download/nginx-1.26.0.tar.gz
# 解压
# tar -xzf nginx-1.26.0.tar.gz
# cd nginx-1.26.0
# 配置编译选项
# ./configure \
–prefix=/etc/nginx \
–sbin-path=/usr/sbin/nginx \
–modules-path=/usr/lib64/nginx/modules \
–conf-path=/etc/nginx/nginx.conf \
–error-log-path=/var/log/nginx/error.log \
–http-log-path=/var/log/nginx/access.log \
–pid-path=/var/run/nginx.pid \
–lock-path=/var/run/nginx.lock \
–user=nginx \
–group=nginx \
–with-http_ssl_module \
–with-http_v2_module \
–with-http_realip_module \
–with-http_addition_module \
–with-http_sub_module \
–with-http_dav_module \
–with-http_flv_module \
–with-http_mp4_module \
–with-http_gunzip_module \
–with-http_gzip_static_module \
–with-http_random_index_module \
–with-http_secure_link_module \
–with-http_stub_status_module \
–with-http_auth_request_module \
–with-mail \
–with-mail_ssl_module \
–with-stream \
–with-stream_ssl_module \
–with-stream_realip_module \
–with-stream_ssl_preread_module \
–with-threads \
–with-file-aio
# 输出示例:
Configuration summary
+ using system PCRE library
+ using system OpenSSL library
+ using system zlib library
# 编译安装
# make -j$(nproc)
# make install
# 验证安装
$ nginx -v
nginx version: nginx/1.26.0
3.3 创建systemd服务
# vi /usr/lib/systemd/system/nginx.service
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
# 重载systemd
# systemctl daemon-reload
# 启动Nginx
# systemctl start nginx
# 设置开机自启
# systemctl enable nginx
# 检查状态
# systemctl status nginx
# 输出示例:
● nginx.service – The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since Sat 2026-04-04 10:00:00 CST; 1s ago
Main PID: 12345 (nginx)
Tasks: 3 (limit: 49134)
Memory: 2.5M
CGroup: /system.slice/nginx.service
├─12345 nginx: master process /usr/sbin/nginx
├─12346 nginx: worker process
└─12347 nginx: worker process
3.4 配置防火墙
# firewall-cmd –permanent –add-service=http
success
# firewall-cmd –permanent –add-service=https
success
# firewall-cmd –reload
success
# 查看开放的端口
# firewall-cmd –list-all
# 输出示例:
public (active)
target: default
icmp-block-inversion: no
interfaces: eth0
sources:
services: cockpit dhcpv6-client http https ssh
ports:
protocols:
forward: no
3.5 验证安装
# netstat -tlnp | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 12345/nginx: master
# 测试访问
$ curl -I http://192.168.1.51
# 输出示例:
HTTP/1.1 200 OK
Server: nginx/1.26.0
Date: Sat, 04 Apr 2026 02:00:00 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Sat, 04 Apr 2026 01:00:00 GMT
Connection: keep-alive
ETag: “6666666-267”
Accept-Ranges: bytes
# 创建测试页面
# echo “Welcome to Nginx on fgedudb01.fgedu.net.cn” > /data/nginx/html/index.html
4. Nginx参数配置
Nginx参数配置是性能优化的关键步骤,直接影响系统性能。更多学习教程公众号风哥教程itpux_com
4.1 主配置文件
# vi /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 65535;
use epoll;
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_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript
application/xml application/xml+rss text/javascript;
include /etc/nginx/conf.d/*.conf;
}
# 检查配置
# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# 重载配置
# nginx -s reload
4.2 性能参数优化
# vi /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
worker_priority -5;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 65535;
use epoll;
multi_accept on;
accept_mutex off;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
charset utf-8;
server_tokens off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 10000;
client_header_timeout 15;
client_body_timeout 15;
send_timeout 15;
client_max_body_size 50m;
client_body_buffer_size 256k;
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
output_buffers 4 32k;
postpone_output 1460;
open_file_cache max=65535 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1k;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css text/xml application/json application/javascript
application/xml application/xml+rss text/javascript application/x-javascript;
include /etc/nginx/conf.d/*.conf;
}
5. 虚拟主机配置
Nginx支持基于IP、端口和域名的虚拟主机配置,本节介绍常用的配置方法。from:www.itpux.com
5.1 基于域名的虚拟主机
# vi /etc/nginx/conf.d/fgedu.conf
server {
listen 80;
server_name www.fgedu.net.cn fgedu.net.cn;
root /data/nginx/html/fgedu;
index index.html index.htm;
access_log /var/log/nginx/fgedu_access.log main;
error_log /var/log/nginx/fgedu_error.log;
location / {
try_files $uri $uri/ =404;
}
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;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
# 创建网站目录
# mkdir -p /data/nginx/html/fgedu
# echo “Welcome to www.fgedu.net.cn” > /data/nginx/html/fgedu/index.html
# 检查并重载配置
# nginx -t && nginx -s reload
5.2 基于端口的虚拟主机
# vi /etc/nginx/conf.d/port8080.conf
server {
listen 8080;
server_name localhost;
root /data/nginx/html/8080;
index index.html index.htm;
access_log /var/log/nginx/port8080_access.log main;
location / {
try_files $uri $uri/ =404;
}
}
# 创建网站目录
# mkdir -p /data/nginx/html/8080
# echo “Welcome to port 8080” > /data/nginx/html/8080/index.html
# 重载配置
# nginx -s reload
# 测试访问
$ curl http://192.168.1.51:8080
Welcome to port 8080
5.3 HTTPS虚拟主机
# mkdir -p /data/nginx/ssl
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /data/nginx/ssl/fgedu.key \
-out /data/nginx/ssl/fgedu.crt \
-subj “/C=CN/ST=BJ/L=BJ/O=FGedu/OU=IT/CN=www.fgedu.net.cn”
# 输出示例:
Generating a RSA private key
writing new private key to ‘/data/nginx/ssl/fgedu.key’
# 创建HTTPS虚拟主机
# vi /etc/nginx/conf.d/fgedu-ssl.conf
server {
listen 443 ssl http2;
server_name www.fgedu.net.cn fgedu.net.cn;
root /data/nginx/html/fgedu;
index index.html index.htm;
ssl_certificate /data/nginx/ssl/fgedu.crt;
ssl_certificate_key /data/nginx/ssl/fgedu.key;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/fgedu_ssl_access.log main;
location / {
try_files $uri $uri/ =404;
}
}
# HTTP重定向到HTTPS
# vi /etc/nginx/conf.d/fgedu-redirect.conf
server {
listen 80;
server_name www.fgedu.net.cn fgedu.net.cn;
return 301 https://$server_name$request_uri;
}
# 重载配置
# nginx -s reload
# 测试HTTPS
$ curl -k https://www.fgedu.net.cn
Welcome to www.fgedu.net.cn
6. 反向代理配置
Nginx作为反向代理服务器是其最重要的功能之一,本节介绍常用的配置方法。更多学习教程www.fgedu.net.cn
6.1 基本反向代理
# vi /etc/nginx/conf.d/proxy.conf
upstream backend_servers {
server 192.168.1.51:8080 weight=3;
server 192.168.1.52:8080 weight=2;
server 192.168.1.53:8080 weight=1;
keepalive 32;
}
server {
listen 80;
server_name api.fgedu.net.cn;
access_log /var/log/nginx/proxy_access.log main;
location / {
proxy_pass http://backend_servers;
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 32k;
proxy_busy_buffers_size 64k;
}
}
# 重载配置
# nginx -s reload
6.2 负载均衡配置
# vi /etc/nginx/conf.d/lb.conf
upstream fgedu_backend {
# 轮询(默认)
# server 192.168.1.51:8080;
# server 192.168.1.52:8080;
# server 192.168.1.53:8080;
# 加权轮询
server 192.168.1.51:8080 weight=3;
server 192.168.1.52:8080 weight=2;
server 192.168.1.53:8080 weight=1;
# IP哈希
# ip_hash;
# server 192.168.1.51:8080;
# server 192.168.1.52:8080;
# 最少连接
# least_conn;
# server 192.168.1.51:8080;
# server 192.168.1.52:8080;
# 健康检查
server 192.168.1.51:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.52:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.53:8080 max_fails=3 fail_timeout=30s backup;
keepalive 32;
}
server {
listen 80;
server_name lb.fgedu.net.cn;
location / {
proxy_pass http://fgedu_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 Connection “”;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
}
}
# 重载配置
# nginx -s reload
6.3 缓存配置
# vi /etc/nginx/nginx.conf
http {
# 缓存配置
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=proxy_cache:100m
max_size=10g inactive=60m use_temp_path=off;
# 其他配置…
}
# 使用缓存
# vi /etc/nginx/conf.d/cache.conf
server {
listen 80;
server_name cache.fgedu.net.cn;
location / {
proxy_pass http://backend_servers;
proxy_cache proxy_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
add_header X-Cache-Status $upstream_cache_status;
}
}
# 创建缓存目录
# mkdir -p /data/nginx/cache
# chown nginx:nginx /data/nginx/cache
# 重载配置
# nginx -s reload
7. 安全配置
Nginx安全配置是保护Web服务的重要措施,本节介绍常用的安全配置方法。学习交流加群风哥微信: itpux-com
7.1 基本安全配置
# vi /etc/nginx/conf.d/security.conf
server {
listen 80;
server_name secure.fgedu.net.cn;
# 隐藏版本号
server_tokens off;
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 禁止访问敏感文件
location ~* \.(git|svn|htaccess|htpasswd|env|config|ini|log|sh|inc|bak|sql)$ {
deny all;
access_log off;
log_not_found off;
}
# 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 防止目录遍历
location ~* \.(?:php|jsp|cgi|pl|py|sh)$ {
deny all;
}
# 安全头部
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 Referrer-Policy “strict-origin-when-cross-origin” always;
location / {
proxy_pass http://backend;
}
}
# 重载配置
# nginx -s reload
7.2 访问控制
# vi /etc/nginx/conf.d/access.conf
server {
listen 80;
server_name admin.fgedu.net.cn;
# 允许指定IP访问
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
proxy_pass http://backend;
}
# 基于密码的访问控制
location /private {
auth_basic “Restricted Area”;
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://backend;
}
}
# 创建密码文件
# htpasswd -c /etc/nginx/.htpasswd admin
New password:
Re-type new password:
Adding password for user admin
# 重载配置
# nginx -s reload
7.3 限流配置
# vi /etc/nginx/nginx.conf
http {
# 限流区域定义
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
# 其他配置…
}
# 应用限流
# vi /etc/nginx/conf.d/rate.conf
server {
listen 80;
server_name api.fgedu.net.cn;
# 请求限流
location /api {
limit_req zone=req_limit burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}
# 连接限流
location /download {
limit_conn conn_limit 10;
limit_conn_status 429;
proxy_pass http://backend;
}
}
# 重载配置
# nginx -s reload
8. 监控与日志
Nginx提供了完善的监控和日志功能,本节介绍常用的监控配置方法。更多学习教程公众号风哥教程itpux_com
8.1 状态监控
# vi /etc/nginx/conf.d/status.conf
server {
listen 80;
server_name localhost;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
}
}
# 重载配置
# nginx -s reload
# 访问状态页面
$ curl http://192.168.1.51/nginx_status
# 输出示例:
Active connections: 10
server accepts handled requests
1000 1000 5000
Reading: 0 Writing: 1 Waiting: 9
8.2 日志配置
# vi /etc/nginx/nginx.conf
http {
log_format main ‘$remote_addr – $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for”‘;
log_format json escape=json ‘{‘
‘”time”:”$time_iso8601″,’
‘”remote_addr”:”$remote_addr”,’
‘”request”:”$request”,’
‘”status”:”$status”,’
‘”body_bytes_sent”:”$body_bytes_sent”,’
‘”request_time”:”$request_time”,’
‘”upstream_response_time”:”$upstream_response_time”,’
‘”http_referer”:”$http_referer”,’
‘”http_user_agent”:”$http_user_agent”‘
‘}’;
access_log /var/log/nginx/access.log main;
}
# 使用JSON日志
# vi /etc/nginx/conf.d/fgedu.conf
server {
listen 80;
server_name www.fgedu.net.cn;
access_log /var/log/nginx/fgedu_access.log json;
location / {
proxy_pass http://backend;
}
}
# 重载配置
# nginx -s reload
8.3 日志分析
$ tail -f /var/log/nginx/access.log
# 输出示例:
192.168.1.100 – – [04/Apr/2026:10:00:00 +0800] “GET / HTTP/1.1” 200 615 “-” “Mozilla/5.0”
192.168.1.101 – – [04/Apr/2026:10:00:01 +0800] “GET /api/users HTTP/1.1” 200 1234 “-” “curl/7.68.0”
# 统计访问量
$ cat /var/log/nginx/access.log | wc -l
10000
# 统计IP访问量
$ awk ‘{print $1}’ /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
# 输出示例:
500 192.168.1.100
300 192.168.1.101
200 192.168.1.102
# 统计HTTP状态码
$ awk ‘{print $9}’ /var/log/nginx/access.log | sort | uniq -c | sort -rn
# 输出示例:
8000 200
1000 304
500 404
200 500
# 日志轮转配置
# vi /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 0640 nginx adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
9. 升级与迁移
Nginx升级和迁移是运维工作中的重要环节,需要仔细规划和执行。from:www.itpux.com
9.1 平滑升级
$ nginx -v
nginx version: nginx/1.24.0
# 下载新版本
# cd /usr/local/src
# wget http://nginx.org/download/nginx-1.26.0.tar.gz
# tar -xzf nginx-1.26.0.tar.gz
# cd nginx-1.26.0
# 配置编译选项(与原版本一致)
# nginx -V
# ./configure [原编译参数]
# 编译(不安装)
# make
# 备份旧版本
# cp /usr/sbin/nginx /usr/sbin/nginx.old
# 替换新版本
# cp objs/nginx /usr/sbin/nginx
# 平滑升级
# kill -USR2 `cat /var/run/nginx.pid`
# 输出示例:
# 新master进程启动,旧master进程重命名为nginx.pid.oldbin
# 关闭旧worker进程
# kill -WINCH `cat /var/run/nginx.pid.oldbin`
# 确认新版本正常后,关闭旧master进程
# kill -QUIT `cat /var/run/nginx.pid.oldbin`
# 验证版本
$ nginx -v
nginx version: nginx/1.26.0
9.2 配置迁移
# tar -czf nginx_conf_backup_$(date +%Y%m%d).tar.gz /etc/nginx /var/log/nginx
# 迁移到新服务器
# scp nginx_conf_backup_*.tar.gz root@newserver:/backup/
# 在新服务器解压
# tar -xzf nginx_conf_backup_*.tar.gz -C /
# 检查配置
# nginx -t
# 输出示例:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# 启动服务
# systemctl start nginx
10. 生产环境实战案例
本节提供一个完整的生产环境配置案例,帮助读者更好地理解Nginx的实际应用。更多学习教程www.fgedu.net.cn
10.1 生产环境完整配置
# vi /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
worker_priority -5;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 65535;
use epoll;
multi_accept on;
accept_mutex off;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
charset utf-8;
server_tokens off;
log_format json escape=json ‘{‘
‘”time”:”$time_iso8601″,’
‘”remote_addr”:”$remote_addr”,’
‘”request”:”$request”,’
‘”status”:”$status”,’
‘”body_bytes_sent”:”$body_bytes_sent”,’
‘”request_time”:”$request_time”,’
‘”upstream_response_time”:”$upstream_response_time”‘
‘}’;
access_log /var/log/nginx/access.log json;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 10000;
client_max_body_size 50m;
client_body_buffer_size 256k;
open_file_cache max=65535 inactive=20s;
open_file_cache_valid 30s;
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1k;
gzip_types text/plain text/css application/json application/javascript;
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=proxy_cache:100m
max_size=10g inactive=60m use_temp_path=off;
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
upstream fgedu_backend {
server 192.168.1.51:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.52:8080 weight=2 max_fails=3 fail_timeout=30s;
server 192.168.1.53:8080 weight=1 max_fails=3 fail_timeout=30s;
keepalive 32;
}
include /etc/nginx/conf.d/*.conf;
}
10.2 高可用负载均衡
# vi /etc/nginx/conf.d/lb.conf
upstream fgedu_web {
least_conn;
server 192.168.1.51:80 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.52:80 weight=2 max_fails=3 fail_timeout=30s;
server 192.168.1.53:80 weight=1 max_fails=3 fail_timeout=30s backup;
keepalive 32;
}
server {
listen 80;
server_name www.fgedu.net.cn fgedu.net.cn;
access_log /var/log/nginx/fgedu_lb_access.log json;
location / {
proxy_pass http://fgedu_web;
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 Connection “”;
proxy_connect_timeout 30s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
proxy_cache proxy_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_key $host$uri$is_args$args;
limit_req zone=req_limit burst=20 nodelay;
add_header X-Cache-Status $upstream_cache_status;
}
}
# 健康检查端点
server {
listen 8080;
server_name localhost;
location /health {
return 200 ‘OK’;
add_header Content-Type text/plain;
}
}
10.3 性能调优实战
# vi /etc/sysctl.d/99-nginx.conf
# 网络优化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 30
# 文件描述符
fs.file-max = 2097152
fs.nr_open = 2097152
# 使配置生效
# sysctl -p /etc/sysctl.d/99-nginx.conf
# 用户限制
# vi /etc/security/limits.d/nginx.conf
nginx soft nofile 65535
nginx hard nofile 65535
nginx soft nproc 65535
nginx hard nproc 65535
# 压力测试
$ ab -n 100000 -c 1000 http://192.168.1.51/
# 输出示例:
Server Software: nginx
Server Hostname: 192.168.1.51
Server Port: 80
Document Path: /
Document Length: 615 bytes
Concurrency Level: 1000
Time taken for tests: 10.000 seconds
Complete requests: 100000
Failed requests: 0
Requests per second: 10000.00 [#/sec] (mean)
Time per request: 100.000 [ms] (mean)
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
