一、nginx 概念 Nginx 是一个高性能的 HTTP 和反向代理 web 服务器,特点占用内存少,并发能力强。反向代理和正向代理 正向代理 是 客户端主动配置的代理服务器,代理客户端向外部服务器发起请求。客户端明确知道自己通过代理访问目标资源。 正向代理典型场景:
突破网络限制(访问被封锁的网站);
隐藏客户端真实 IP(匿名上网);
企业内网统一管控外网访问反向代理 是 服务端部署的代理服务器,代理后端真实服务器接收客户端请求。客户端不知道后端服务器的存在,认为反向代理就是实际服务提供者。 反向代理典型场景:
负载均衡(将请求分发到多个后端服务器);
隐藏真实服务器 IP(提升安全性);
统一 SSL 加密/缓存/压缩(减轻后端压力)。
二、nginx 安装 nginx 安装可以使用 yum 安装和源码包安装,在工作中使用源码包安装会多一点
(一) yum 安装
yum 安装 nginx
1 2 [root@localhost ~]# yum -y install https://nginx.org/packages/centos/7/x86_64/RPMS/nginx-1.18.0-2.el7.ngx.x86_64.rpm
查看是否安装成功
1 [root@localhost ~]# rpm -qa|grep nginx
查看安装后产生的文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 [root@localhost ~]# rpm -ql nginx-1.18.0-2.el7.ngx.x86_64 /etc/logrotate.d/nginx 重点/etc/nginx/nginx.conf 重点/etc/nginx/conf.d 重点/etc/nginx/conf.d/default.conf /etc/nginx/fastcgi_params /etc/nginx/scgi_params /etc/nginx/uwsgi_params /etc/nginx/koi-utf /etc/nginx/koi-win /etc/nginx/win-utf /etc/nginx/mime.types /etc/nginx/modules /etc/sysconfig/nginx /etc/sysconfig/nginx-debug /usr/lib/systemd/system/nginx-debug.service /usr/lib/systemd/system/nginx.service 重点/usr/sbin/nginx /usr/sbin/nginx-debug /usr/share/doc/nginx-1.18.0 /usr/share/doc/nginx-1.18.0/COPYRIGHT /usr/share/man/man8/nginx.8.gz /usr/share/nginx 重点/usr/share/nginx/html /usr/share/nginx/html/50x.html /usr/share/nginx/html/index.html /var/cache/nginx 重点/var/log/nginx /usr/lib64/nginx
启停 nginx
1 2 3 4 5 6 [root@localhost ~]# systemctl start nginx [root@localhost ~]# systemctl enable nginx [root@localhost ~]# systemctl stop nginx
访问 nginx 启动后可以打开浏览器,输入 http://ip:port 即可访问 nginx 主页面,注意:http 端口默认是 80,所以访问是可以不输入 端口号 5.卸载 nginx
1 [root@localhost ~]# yum -y remove nginx-1.18.0-2.el7.ngx.x86_64
(二) 源码包安装
创建一个文件夹,存放安装的 nginx 文件
安装 nginx 依赖包
1 yum -y install gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel
下载并解压 nginx 源码包
1 2 3 4 5 6 7 8 mkdir /opt/soft/nginx -p && cd /opt/soft/nginxwget https://nginx.org/download/nginx-1.18.0.tar.gz tar -zxvf nginx-1.18.0.tar.gz cd nginx-1.18.0
配置编译并安装
1 2 3 4 5 6 7 8 9 10 11 12 ./configure --user=root --group=root --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --with-http_sub_module --with-stream \ --with-stream_ssl_module \ --with-openssl-opt=enable-weak-ssl-ciphers make make install
根据以上编译安装,安装后的所有文件会存放在/usr/local/nginx
更多编译参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 --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 --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protectorstrong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
启停 nginx
1 2 3 4 5 6 7 8 9 10 cd /usr/local/nginx/sbin./nginx /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx -s reload /usr/local/nginx/sbin/nginx -s stop
设置 system
1 2 3 4 5 6 7 8 9 10 11 12 13 vim /lib/systemd/system/nginx.service [Unit] Description=nginx service After=network.target [Service] Type=forking ExecStart=/usr/local/nginx/sbin/nginx ExecReload=/usr/local/nginx/sbin/nginx -s restart ExecStop=/usr/local/nginx/sbin/nginx -s stop PrivateTmp=true [Install] WantedBy=multi-user.target
启动并设置开机自启
1 systemctl enable nginx && systemctl start nginx
nginx 进程模型
master 主进程
master 用于管理 worker
worker 工作进程
worker 是为 master 进行服务的
三、Nginx 基本配置 1.nginx 配置文件组成 yum 安装的配置文件路径:/etc/nginx 源码包安装的配置文件路径:/usr/local/nginx/conf nginx 的主配置文件:nginx.conf
核心模块,进程数等
1 2 3 4 5 user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid;
事件驱动,工作模块等
1 2 3 4 events { worker_connections 1024; }
http 内核模块,文档程序类型等,配置文件等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 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; keepalive_timeout 65; 长连接 include /etc/nginx/conf.d/\*.conf; }
2.nginx 子配置文件配置结构 路径:/etc/nginx/conf.d/default.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location ~ \.php$ { root /usr/share/nginx/html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name ; include fastcgi_params; } }
3.合整默认配置文件内容 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
4.静态资源服务举例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } location /www { root /home; } location /www { alias /home/www; } }
5.域名解析 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 server { listen 80; server_name www.web.com; location / { root html; index index.html index.htm; } } server { listen 80; server_name www.web.com www.nginxweb.com; location / { root html; index index.html index.htm; } }
6.多站点 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 server { listen 80; server_name www.web.com; location / { root html; index index.html index.htm; } } server { listen 80; server_name www.web2.com; location / { root /www; index index.html index.htm; } }
7.连接状态 可以统计出网页被多少用户连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 server { listen 80 ssl; server_name localhost; location / { root html; index index.html index.htm; } location /nginx_status{ stub_status; allow all; } } ip:端口/nginx_ststus
四、Nginx 日志管理 1.nginx 日志概念 nginx 日志是由 nginx 日志模块进行配置的,日志文件模块:ngx_http_log_module nginx 默认有两种日志:
access_log #访问日志,统计用户访问信息
error_log #错误信息日志
yum 安装的日志路径:/var/log/nginx
源码包安装日志路径:/usr/local/nginx/logs
2.日志格式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"' ; $remote_addr 远程地址,记录访问者IP地址;$remote_user 访问用户;[$time_local ] 服务器本地时间;$request 记录请求协议; $status 请求状态;$body_bytes_sent 访问字节数;$http_referer 从哪里链接过来的;$http_user_agent 记录客户端浏览器信息;$http_x_forwarded_for 代理ip;log_format json '{' '"remote_addr": "$remote_addr", ' '"remote_user": "$remote_user", ' '"time_local": "$time_local", ' '"request": "$request", ' '"status": "$status", ' '"body_bytes_sent": "$body_bytes_sent", ' '"http_referer": "$http_referer", ' '"http_user_agent": "$http_user_agent", ' '"http_x_forwarded_for": "$http_x_forwarded_for"' '}' ;
3.日志轮转 轮转的作用是把一个大的日志割接成多个小的日志,否者日志太大不利于观察等。一般一天切割一次,错误日志一般 不需要切割
割接脚本
1 2 3 4 5 6 7 8 log *path="/usr/local/nginx/logs/" recode_time=$(date -d "yesterday" +%Y-%m-%d+%H:%M) pid=/usr/local/nginx/logs/nginx.pid mv ${log_path} /access.log ${log_path} /access.${recode_time} .log mv ${log_path} /error.log ${log_path} /error.${recode_time} .log kill -USR1 `cat $pid `
添加定时切割
1 2 crontab -e */1 \_ \* \* \* /usr/local/nginx/sbin/nginx_logrotate.sh
五、反向代理 1.反向代理的配置 1 2 3 4 5 6 7 server { listen 80; server_name www.web.com; location / { proxy_pass http://www.baidu.com; } }
proxy 模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 proxy_pass URL; proxy_redirect default; proxy_set_header Host $proxy_host ; proxy_set_header X-Real-IP $remote_addr ; proxy_cache_path /tmp/nginx/cache levels=1:2 keys_zone=proxy_cache:10m max_size=10g inactive=60m use_temp_path=off; proxy_cache proxy_cache; proxy_cache_valid 200 304 12h; proxy_cache_valid any 10m; proxy_cache_key $host$uri$is_args$args ; add_header Nginx-Cache "$upstream_cache_status " ; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; proxy_buffering on; proxy_buffer_size 32k; proxy_buffers 4 128k; proxy_busy_buffers_size 256k; proxy_max_temp_file_size 256k;
2.负载均衡 Nginx 作为一款高性能的反向代理服务器和负载均衡器,被广泛用于分发客户端请求到多个后端服务器,以提高系统 的可用性、扩展性和容错能力。 负载均衡的作用:
流量分发:将客户端请求均匀分发到多个服务器,避免单点过载。
高可用性:自动检测后端服务器状态,故障时自动剔除不可用节点。
横向扩展:通过添加服务器提升系统整体处理能力。
会话保持:支持会话粘滞(如基于 Cookie 或 IP),确保用户请求路由到同一服务器。 负载均衡分类:
四层负载均衡: 层级:基于 OSI 模型的传输层(Layer 4),主要处理 TCP/UDP 流量。 特点:仅根据 IP 地址和端口号进行流量分发,不解析应用层协议内容。 适用场景:数据库、SSH、游戏服务器、实时通信等 TCP/UDP 协议场景。
1 2 3 4 5 6 7 8 9 10 11 12 stream { upstream backend_tcp { server 192.168.1.10:3306; server 192.168.1.11:3306; } server { listen 3306; proxy_pass backend_tcp; } }
七层负载均衡: 层级:基于 OSI 模型的应用层(Layer 7),支持解析 HTTP/HTTPS、SMTP 等协议。 特点:根据应用层内容(如 URL、Cookie、Header、请求体)进行流量分发。 适用场景:Web 服务器、API 网关、微服务路由、基于内容的缓存和过滤。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 http { upstream backend_http { server 192.168.1.10:80; server 192.168.1.11:80; } server { listen 80; location / { proxy_pass http://backend_http; proxy_set_header Host $host ; if ($request_uri ~\* "/api/" ) { proxy_pass http://api_servers; } } } }
2.1 轮训 默认策略:请求按顺序依次分发到后端服务器。
1 2 3 4 5 6 7 8 9 10 11 12 13 upstream heber{ server 192.168.0.118:8080; server 192.168.0.119:8080; } server { listen 80; server_name www.web.com; location / { proxy_pass http://heber; } }
2.2 加权轮询 按权重分配:为性能不同的服务器分配不同权重(权重越高,处理更多请求)。
1 2 3 4 5 6 7 8 9 10 11 12 13 upstream heber{ server 192.168.0.118:8080 weight=3; server 192.168.0.119:8080 weight=2; server 192.168.0.120:8080 weight=1; } server { listen 80; server_name www.web.com; location / { proxy_pass http://heber; } }
2.3 最少连接 动态分配:将请求分发给当前连接数最少的服务器。
1 2 3 4 5 6 7 8 9 10 11 12 13 upstream heber{ least_conn; server 192.168.0.118:8080; server 192.168.0.119:8080; } server { listen 80; server_name www.web.com; location / { proxy_pass http://heber; } }
2.4 upstream 参数指令
1 2 3 max_conns 最大连接数 slow_start 让集群缓慢启动 down 不参与负载 backup 表示备用机 max_fails 最大失败次数 fail_timeout 失败时间段
3.维持会话 当我们使用 upstream 去做负载均衡后,我们在登录的时候就会登录不上,这个时候我们的负载就需要添加 ip_hash 算法进行分配即可
1 2 3 4 5 6 7 8 9 10 11 12 13 upstream heber{ ip_hash; server 192.168.0.118:8080; server 192.168.0.119:8080; } server { listen 80; server_name www.web.com; location / { proxy_pass http://heber; } }
4.缓冲区 Nginx 的 缓冲区(Buffering) 是一种临时存储数据的机制,用于在处理客户端请求或代理响应时平衡内存使用与性能。合理配置缓冲区可以优化吞吐量、防止资源耗尽,但不当配置可能导致内存溢出或延迟问题。缓冲区的配置可以配置在 http,server,location 中。4.1 缓冲区的作用 临时存储数据 当客户端上传大文件(如上传视频)时,Nginx 先将数据缓存在内存或磁盘,再分块传递给后端。 当反向代理时,Nginx 先完整接收后端响应逐步返回给客户端。 提升性能 减少频繁的 I/O 操作,尤其在高并发场景下能降低系统负载。 保护后端服务 避免慢客户端(如低速网络用户)长时间占用后端连接。4.2 客户端请求缓冲区(处理客户端 →Nginx 的数据)
1 2 3 4 5 6 7 http { client_body_buffer_size 16k; client_body_in_file_only off; client_max_body_size 100M; }
4.3 代理缓冲区(处理 Nginx→ 上游服务器的数据)
1 2 3 4 5 6 7 8 9 10 11 12 http { proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 16k; proxy_max_temp_file_size 1024m; proxy_temp_file_write_size 64k; proxy_busy_buffers_size 32k; }
4.4 示例配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 http { client_max_body_size 2G; client_body_buffer_size 256k; proxy_buffering on; proxy_buffer_size 16k; proxy_buffers 16 1M; proxy_max_temp_file_size 4G; proxy_temp_file_write_size 128k; upstream backend { server 10.0.0.1:8080; } server { location /upload { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Connection "" ; } } }
5.代理头信息 在 Nginx 中,代理头信息(Proxy Headers)是指通过反向代理将客户端请求转发到后端服务器时,修改或添加的 HTTP 请求头信息。这些头信息对后端服务器正确处理请求、识别客户端真实信息以及保障安全至关重要。5.1 基础头信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 upstream heber{ ip_hash; server 192.168.0.118:8080; server 192.168.0.119:8080; } server { listen 80; server_name www.web.com; location / { proxy_pass http://heber; proxy_set_header Host $host ; proxy_set_header X-Forwarded-For $remote_addr ; proxy_set_header X-Forwarded-Proto $scheme ; proxy_connect_timeout 60s; proxy_read_timeout 600s; } }
5.2 高级场景与配置
处理 WebSocket 代理 WebSocket 需要额外头信息维持长连接:
1 2 3 4 5 6 location /ws/ { proxy_pass http://websocket_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade ; proxy_set_header Connection "upgrade" ; }
5.3 自定义头信息
向后端传递自定义头(如认证 Token):
1 proxy_set_header Authorization "Bearer $http_authorization " ;
5.4 防止头信息被覆盖
确保代理不覆盖后端设置的头:
1 proxy_pass_request_headers on;
六、动静分离 Nginx 的 动静分离 是一种优化 Web 应用性能的常见策略,核心思想是将静态资源(如图片、CSS、JS 文件)和动态内容(如 API 接口、动态生成页面)分别由不同的服务器或处理逻辑处理,从而提高整体系统的响应速度和资源利用率。
1.动静分离的作用
(1) 提升性能 静态资源:直接由 Nginx 本地处理(或通过 CDN 分发),无需经过后端应用服务器,减少延迟。 动态请求:仅转发到后端应用服务器(如 Tomcat、Node.js),避免静态资源占用后端处理能力。
(2) 降低服务器压力 静态资源通常占网站流量的 70% 以上,分离后显著减少后端服务器的负载。 Nginx 擅长高并发静态文件处理,避免应用服务器因频繁 I/O 操作成为瓶颈。
(3) 优化缓存策略 可对静态资源设置长期缓存(如 Cache-Control: maxage=31536000),减少重复请求。 动态内容可单独配置缓存策略(如短时间缓存或无缓存)。
(4) 提升扩展性 静态资源可独立部署到 CDN 或对象存储(如 AWS S3、阿里云 OSS),动态服务单独横向扩展。
2.动静分离的配置实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 server { listen 80; server_name www.web.com; location ~\* \.(jpg|jpeg|gif|png|css|js|ico|webp|svg|images)$ { root html; expires 365d; access_log off; } location / { proxy_pass http://backend_server; proxy_set_header Host $host ; proxy_set_header X-Real-IP $remote_addr ; } }
七、http 和 https HTTP(HyperText Transfer Protocol)和 HTTPS(HTTP Secure)是用于客户端与服务器之间传输数据的核心协议,广泛应用于 Web 通信。 HTTP:
无状态:每次请求独立,不保留会话信息(需 Cookie/Session 扩展)。
明文传输:数据未经加密,易被窃听、篡改(如中间人攻击)攻击者可注入广告或恶意代码。
默认端口:80。 HTTPS:
在 HTTP 基础上通过 SSL/TLS 加密实现安全通信。
加密传输:数据加密后传输,防止窃听和篡改。
身份认证:通过数字证书验证服务器身份。
完整性校验:确保数据在传输中未被修改。
1.https 配置 #安装需要秘钥生成软件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 yum -y install openssl openssl-devel openssl genrsa -out cert.key 2048 genrsa RSA 类型 -out cert.key 密钥存放在哪个文件 2048 密钥的长度 越长越安全 openssl req -new -key cert.key -out cert.csr -days 365 -new 申请新的证书 -key cert.key 密钥的路径 -out cert.csr 申请证书的路径 -days 365 证书的有效期 openssl x509 -req -in cert.csr -signkey cert.key -out cert.pem -days 365 x509 颁发证书的 -in cert.csr 申请证书 -signkey cert.key 密钥 -out cert.pem 证书的名字 -days 365 有效时间 cp ~/cert.key /nginx/confcp ~/cert.pem /nginx/conf server { listen 443 ssl; server_name localhost; ssl_certificate cert.pem; ssl_certificate_key cert.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; location / { root html; index index.html index.htm; } }
2.http 重定向 https 1 2 3 4 5 server { listen 80; server*name xxx.com; rewrite ^(.*) https://$server_name$request \*uri? permanent ; }
八、nginx 模块 1.模块介绍 Nginx 采用模块化架构,通过不同的模块实现灵活的功能扩展。总体模块可以分为核心模块、常用官方模块及第三方模块。在安装 nginx 会默认安装一些模块,如果需要其他模块可以手动编译添加第三方模块下载地址:https://bitbucket.org/nginx-goodies/nginx-sticky-module-ng/ 查看模块方法
1 2 3 /usr/local/nginx/sbin/nginx -V 或者 /usr/local/nginx/sbin/nginx -V 2>&1 | grep 'configure arguments:'
2.模块添加 #切换到源码包文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 cd /opt/soft/nginx/nginx-1.18.0 ./configure \ --user=root --group=root --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --with-http_sub_module \ --with-stream \ --with-stream_ssl_module \ --with-openssl-opt=enable-weak-ssl-ciphers \ --add-module=/path/to/third-party-module \ --with-http_geoip_module make /usr/local/nginx/sbin/nginx -s stop cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak cp objs/nginx /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx -V 2>&1 | grep 'configure arguments:' ``` ```bash 随机微更新网页,所需模块:random_index_module location / { root /app random_index on; }
4.替换模块 1 2 3 快速替换文件内容,所需模块:sub_module sub_filter nginx "he_ber" ; sub_filter_once on;
5.文件读取
6.文件压缩 所需模块:--with-http_gzip_static_module gzip 配置
1 2 3 4 5 6 7 8 gzip on; gzip_min_length 1; gzip_comp_level 3; gzip_types text/plain text/css;
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 server { listen 80; server_name localhost; client_max_body_size 500M; gzip on; gzip_http_version 1.0; gzip_disable 'MSIE [1-6]' ; gzip_types image/jpeg image/png image/jpg application/javascript text/css; location / { expires 3d; proxy_pass http://ip:port; 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 ; } }
7.页面缓存 控制页面缓存作用,可以减少服务器的请求
2.上游服务器缓存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 upstream heber{ server 192.168.0.118:8080; server 192.168.0.119:8080; } proxy_cache_path /nginx/upsteam_cache keys_zone=mycache:5m max_size=1g inactive=1h use_temp_path=off; server { listen 80; server_name www.he_ber.com; proxy_cache mycache; proxy_cache_valid 200 304 8h; location / { proxy_pass http://heber; } }
8.防盗链
防盗链可以防止人家使用图片链接等
1 2 3 4 5 6 7 location ~*/(jpg|jpeg|gif|png|css|js|ico|webp|svg|images) { valid*referers none *.heber.com; if ($invalid \*referer){ return 404; }
九、平滑升级 Nginx 的平滑升级停止服务即可更新 Nginx 版本或重新加载配置的技术。通过保留旧进程处理已建立的连接,同时启动新进程接受新请求,实现 零停机时间的更新操作。
1.方式一 #切换目录 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 cd /opt/soft/nginx wget https://nginx.org/download/nginx-1.20.0.tar.gz tar -zxvf nginx-1.20.0.tar.gz cd nginx-1.20.0 ./configure --user=root --group=root --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --with-http_sub_module --with-stream \ --with-stream_ssl_module \ --with-openssl-opt=enable-weak-ssl-ciphers make && make install ps -ef|grep nginx kill -USR2 主进程号 kill -WINCH 旧的主进程号kill -QUIT 旧的主进程号 [root@localhost /usr/local/nginx/sbin]# nginx -v nginx version: nginx/1.20.0
2.方式二 #切换目录 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 cd /opt/soft/nginx wget https://nginx.org/download/nginx-1.20.1.tar.gz tar -zxvf nginx-1.20.1.tar.gz cd nginx-1.20.1 ./configure --user=root --group=root --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --with-http_sub_module --with-stream \ --with-stream_ssl_module \ --with-openssl-opt=enable-weak-ssl-ciphers make install && make upgrade [root@localhost /usr/local/nginx/sbin]# nginx -v nginx version: nginx/1.20.1
十、访问配置 1.访问限制
限制不是完全不能访问,只是限制掉一些条件请求
ngx_http_limit_req_module 限制 http 请求
1 2 3 4 5 yum -y install httpd-tools ab -n 100 -c 10 http://ip:端口 limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s; limit_req zone=req_zone;
ngx_http_limit_conn_module 限制 tcp 链接
1 2 3 4 5 6 limit_conn_zone $binary_remote_addr zone=conn_zone:10m; limit_conn conn_zone 1; 2.访问控制 控制直接封 ip 或者用户 allow 192.168.0.\*;#允许访问的 deny all;#封杀的
十一、nginx 集群 集群有很多种,可以分为:负载均衡,高可用,高性能存储。
1.负载均衡集群 LVS 负载均衡增加处理能力,有一定的高可用能力,但不是高可用集群,是以提高服务的并发处理能力为主。这里使用的 是软件负载均衡设备 lvs(四层路由设备)。实现负载均衡一般可以使用顺序,流量,比重服务等类型进行分配,lvs 工作模式:nat 转发模式,DR 直接路由模式,隧道模式,full 模式。
nat 转发模式
优点:网络隔离更安全,节约 ip 地址
缺点:访问量大了很可能成为系统瓶颈
lvs 安装
1 2 3 4 5 echo 1 >/proc/sys/net/ipv4/ip_forwardipvsadm -A -t 外网 ip -s rr#对外服务器 ipvsadm -a -t 公网 ip -r web1ip -m#对内真实 webip ipvsadm -a -t 公网 ip -r web2ip -m
DR 直接路由模式 针对同一网段或都是公网 ip
1 2 3 4 5 6 7 ifconfig ens32:0 虚拟 ip broadcast 虚拟 ip 网络到 255 netmask 255.255.255.0 route add -host 虚拟 ip dev ens32:0 vim /etc/sysctl.conf net.ipv4.ip_forward=1
1 2 3 4 5 6 7 8 9 10 11 12 ipvsadm -C ipvsadm -A -t 外网 ip:端口 -s rr#对外服务器 ipvsadm -a -t 公网 ip:端口 -r web1ip:端口 -g#对内真实 webip ipvsadm -a -t 公网 ip:端口 -r web2ip:端口 -g -A 添加 vip -t 指定使用 tcp -s 指定调度策略 -a 添加真实 reallserver -r 指定具体 reallserver 是谁 -g lvs 类型 DR ipvsadm-save > /etc/sysconfig/ipvsadm
4.给 web 服务器 lo 网卡设置子网掩码为 32 位 vip
轮巡
2.高可用 keepalived 使用 keepalived 可以产生一个虚拟 ip,用户访问时也是访问虚拟 ip,就算集群的机器挂了一台访问虚拟 ip 一样可以访问,从而达到高可用集群。(vip 就是 keepalived 的虚拟 ip)
安装 keepalived
1 2 3 4 5 6 7 8 9 10 11 12 tar -zxvf keepalived-2.0.18.tar.gz mkdir /nginx/keepalivedyum -y install libnl libnl-devel ./configure --prefix=/nginx/keepalived --sysconf=/etc make && make install whereis keepalived
配置 keepalived
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 vim /etc/keepalived/keepalived.conf ! Configuration File for keepalived global_defs { notification_email { acassen@firewall.loc failover@firewall.loc sysadmin@firewall.loc } notification_email_from Alexandre.Cassen@firewall.loc smtp_server 192.168.200.1 smtp_connect_timeout 30 router_id keep_118 vrrp_skip_check_adv_addr vrrp_strict vrrp_garp_interval 0 vrrp_gna_interval 0 } vrrp_script check_nginx_alived { script "/etc/keepalived/check_nginx_alivd_or_not.sh" interval 2 weigth 10 } vrrp_instance VI_1 { state MASTER interface ens33 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1111 } track_script { check_nginx_alived } virtual_ipaddress { 192.168.0.120 } }
启动 keepalived
1 2 cd /nginx/keepalived/sbin./keepalived
设置开机自启
1 2 3 4 5 cd /opt/keepalived-2.0.18/keepalived/etccp init.d/keepalived /etc/init.d/cp sysconfig/keepalived /etc/sysconfig/systemctl daemon-reload systemctl enable keepalived
备用节点配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ! Configuration File for keepalived global_defs { router_id keep_119 } vrrp_instance VI_1 { state BACKUP interface ens33 virtual_router_id 51 priority 80 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.0.120 } }
配置 keepalived 重启 nginx
1 2 3 4 5 6 7 8 9 10 11 12 vim check_nginx_alivd_or_not.sh ng=`ps -C nginx --no-header |wc -l` if test $ng -eq 0 ;then /nginx/sbin/nginx sleep 3 if test `ps -C nginx --no-header |wc -l` -eq 0 ;then killall keepalived fi fi
双主热备
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 vrrp_instance VI_2 { state MASTER interface ens3 virtual_router_id 52 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.0.121 } } vrrp_instance VI_2 { state BACKUP interface ens33 virtual_router_id 52 priority 80 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.0.121 } }