前言
在当今的互联网时代,Web 服务器扮演着至关重要的角色。Nginx
,作为一款高性能、高可靠性的 Web 服务器
和反向代理服务器
,已经成为许多大型网站和应用的首选。本文将介绍 Nginx 的架构、配置文件、实践案例,包括负载均衡、安全配置如 CSP 和 HTTPS,以及代理 wss 等高级特性,展示了 Nginx 在现代 Web 服务中的广泛应用和强大功能。
Nginx 介绍
Nginx 的特点
- 高性能:Nginx 采用
事件驱动
和异步非阻塞
的处理方式,能够支持数以万计的并发连接。 - 高可靠性:Nginx 的
Master-Worker
结构设计,使得其中一个 Worker 进程出现问题时,不会影响到整个服务器的运行。 - 模块化设计:Nginx 具有丰富的
模块系统
,可以通过安装第三方模块来扩展功能。 - 配置简单:Nginx 的配置文件简洁明了,
易于理解和管理
。
Nginx 架构
Master-Worker 结构
Nginx 的 Master 进程
负责管理 Worker 进程
,Worker 进程负责处理实际的网络请求。这种设计提高了 Nginx 的稳定性和扩展性。
事件驱动
Nginx 使用事件驱动模型来处理连接,这意味着它能够同时处理多个网络连接,而不需要为每个连接创建一个线程或进程。
异步非阻塞
Nginx 的异步非阻塞特性使得它能够在等待某个操作完成时继续处理其他请求,从而提高了效率。
Nginx 配置文件介绍
Nginx 的配置文件通常位于/etc/nginx/nginx.conf
,它是 Nginx 运行的基础。
基本配置指令
worker_processes
:设置 Worker 进程的数量。events
:配置事件模块,如连接数限制。http
:包含 HTTP 服务器的配置指令。
nginx.conf
#user nobody; #用户组
worker_processes 1; # 只启动一个工作进程
events {
worker_connections 1024; # 每个工作进程的最大连接为1024
}
http {
include mime.types; # 引入MIME类型映射表文件
default_type application/octet-stream; # 全局默认映射类型为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;
sendfile on; # 启用零复制机制
keepalive_timeout 65; # 保持连接超时时间为65s
server {
listen 80; # 监听80端口的网络连接请求
server_name localhost; # 虚拟主机名为localhost
#charset koi8-r;
#access_log logs/host.access.log main;
location / { # 匹配规则
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
实践案例
条件判断
server {
// if的这个空格不能省
if ($host = test.jiatingyu.top) {
return 301 https://$host$request_uri;
}
server_name test.jiatingyu.top;
return 404;
}
查看 nginx 中的内置变量 , 内部变量打印
直接在请求的 url header 中添加返回
// 官方文档 变量查看地址
// https://nginx.org/en/docs/http/ngx_http_core_module.html#variables
// document --- Modules reference --- ngx_http_core_module -- Embedded Variables
add_header x1-NGINX-http_user_agent $http_user_agent;
add_header xA-NGINX-http_cookie $http_cookie;
add_header xB-NGINX-request $request;
抽离出一个 debug-headers.conf
文件,通过 include 引入
location = / {
include debug-headers.conf; // 这里就可以把所有自定义的header 写在里面
}
自定义返回格式 html 或 json
location / {
# default_type text/html;
# return 200 "hello html";
default_type application/json;
return 200 "{'msg':'hello json'}";
}
负债均衡
// 三种权重 轮询、weight、ip_hash ;
upstream mysvr {
server 127.0.0.1:7878 weight=1; //权重
server 192.168.10.121:3333 weight=2;
server 192.168.10.121:3333 backup; //热备 后备服务器,其他坏了才进这个
// ip_hash; // # 启用IP哈希负载均衡策略, 相同ip只进相同的服务器
}
location / {
proxy_pass http://mysvr;
}
nginx htpasswd 的认证
server {
listen 80;
# 所有路径都加验证
; auth_basic "请输入用户名和密码";
; auth_basic_user_file ../jty;
location / {
include debug-headers.conf;
}
location /api/ {
# 只对api 路径进行限制,文件相对于nginx的conf目录
auth_basic "请输入用户名和密码";
auth_basic_user_file ../jty;
proxy_pass http://47.105.202.15:8077/;
}
}
静态文件索引
server {
listen 80;
location / {
root D:/download/;
sendfile on; # 开启高效文件传输模式(零拷贝)
autoindex on; # 开启目录文件列表
autoindex_exact_size off; # 显示出文件的确切大小,单位是bytes
autoindex_localtime on; # 显示的文件时间为文件的服务器时间
charset utf-8,gbk; # 避免中文乱码
}
}
路径别名
alias 与 root 的区别:
- alias: alias 指定的目录是准确的,alias 指定的目录后面必须要加上
/
符号!! - root : location 匹配的 path 目录后面带不带
/
,都不会影响访问。
location /file/ {
alias E:/nginx-1.24.0/html/;
index index.html;
}
IP 限制
location ~ /js/ {
root html;
index index.html;
try_files $uri $uri/ /index.html;
# 标识除了允许的,其他的全部拒绝(---位置不能换---),如果有多个就复制行 , 0/8 是指统配前三位 、16 前两位 、24 前一位
allow 192.168.124.0/24;
deny all; #拒绝的ip
}
return、rewrite 和 try_files 指令
location /api1/ {
# 302 重定向
return http://baidu.com;
}
location /api2/ {
# 重写url
rewrite ^/api/(.*)$ http://xxxxx:8077/$1 break;
}
location /api3/ {
# 反向代理 不重写
proxy_pass http://xxxxx:8077/;
}
location 规则
=
:精确匹配,优先级最高。如果找到了这个精确匹配,则停止查找。^~
:URI 以某个常规字符串开头,不是正则匹配~
:区分大小写的正则匹配~*
:不区分大小写的正则匹配/
:通用匹配, 优先级最低。任何请求都会匹配到这个规则
优先级为: =
> 完整路径
> ^~
> ~、~*
> /
网站安全
CSP 安全配置
location / {
add_header X-Frame-Options SAMEORIGIN;
# https://wangshuashua.com/nginx-configcspcontent-security-policy 参考文档
# add_header Content-Security-Policy "default-src 'self'; script-src 'self' *.amap.com *.qq.com *.jquery.com *.bdimg.com; connect-src 'self'; img-src 'self' data:; style-src 'self';frame-ancestors 'none'; form-action 'none';";
add_header Content-Security-Policy "default-src 'self' 125.65.86.164:9001 'unsafe-inline';script-src 'self' 'unsafe-eval' unpkg.com;img-src 'self' data: ";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options nosniff;
add_header Strict-Transport-Security "max-age=31536000; preload; includeSubDomains" always;
}
Https
server {
#SSL 默认访问端口号为 443
listen 443 ssl;
#请填写绑定证书的域名
server_name xx.jiatingyu.top;
#请填写证书文件的相对路径或绝对路径
ssl_certificate xx.jiatingyu.top.crt;
#请填写私钥文件的相对路径或绝对路径
ssl_certificate_key xx.jiatingyu.top.key;
ssl_session_timeout 5m;
#请按照以下套件配置,配置加密套件,写法遵循 openssl 标准。
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location / {
#网站主页路径。此路径仅供参考,具体请您按照实际目录操作。
#例如,您的网站主页在 Nginx 服务器的 /etc/www 目录下,则请修改 root 后面的 html 为 /etc/www。
root html;
index index.html index.htm;
}
}
代理 wss
location /wss/ {
proxy_pass http://xxxx:9884/mqtt/;
proxy_set_header Sec-WebSocket-Protocol mqtt;
proxy_http_version 1.1;
proxy_set_header Upgrade websocket;
proxy_set_header Connection "upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
}
小结:
Nginx 是一种高性能、高可靠性的 Web 服务器,采用事件驱动和异步非阻塞模型,支持大量并发连接。它具有模块化设计,配置简单,易于扩展。本文介绍了 Nginx 的架构、配置文件、实践案例,包括负载均衡、安全配置如 CSP 和 HTTPS,以及代理 wss 等高级特性,展示了 Nginx 在现代 Web 服务中的广泛应用和强大功能。