当前位置: 首页 > news >正文

Nginx完全学习指南 - 从入门到实战

目录

什么是Nginx?

为什么要使用Nginx?

Nginx安装

Nginx基本概念

配置文件详解

静态文件服务

反向代理

负载均衡

虚拟主机

HTTPS配置

缓存配置

日志管理

性能优化


什么是Nginx?

简单理解

想象一下,Nginx就像一个超级智能的门卫

  • 普通门卫:只能开门关门,让人进出
  • Nginx门卫:不仅能控制进出,还能:
    • 把访客引导到正确的房间(路由)
    • 当某个房间人太多时,引导到其他房间(负载均衡)
    • 帮访客取文件(静态文件服务)
    • 代替房间主人接待客人(反向代理)
    • 记录谁来过、什么时候来的(日志)

技术定义

Nginx(发音:engine-x)是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。它具有以下特点:

  • 轻量级:占用内存少,启动快
  • 高并发:能同时处理大量连接
  • 高性能:处理静态文件效率极高
  • 稳定性:很少崩溃,运行稳定
  • 模块化:功能通过模块扩展

为什么要使用Nginx?

1. 性能优势

Apache vs Nginx 处理能力对比:
Apache: 适合处理动态内容,但并发能力有限
Nginx:  处理静态内容速度快,并发能力强举例:
- Apache: 像传统餐厅,一个服务员服务一桌客人
- Nginx:  像现代快餐店,一个收银员可以同时处理多个订单

2. 资源消耗低

内存使用对比:
Apache: 每个连接消耗大量内存
Nginx:  所有连接共享少量内存比喻:
- Apache: 每个客人都要单独的包间
- Nginx:  所有客人可以在大厅里,按需分配座位

3. 配置简单

配置文件对比:
Apache: 配置文件复杂,指令多
Nginx:  配置文件简洁,逻辑清晰

4. 适用场景

  • 静态文件服务:图片、CSS、JS文件
  • 反向代理:隐藏后端服务器
  • 负载均衡:分发请求到多个服务器
  • API网关:统一入口管理
  • 缓存服务:减少后端压力

Nginx安装

Ubuntu/Debian系统

# 更新包列表
sudo apt update# 安装nginx
sudo apt install nginx# 启动nginx
sudo systemctl start nginx# 设置开机自启
sudo systemctl enable nginx# 检查状态
sudo systemctl status nginx

CentOS/RHEL系统

# 安装EPEL源
sudo yum install epel-release# 安装nginx
sudo yum install nginx# 启动nginx
sudo systemctl start nginx# 设置开机自启
sudo systemctl enable nginx# 检查状态
sudo systemctl status nginx

源码编译安装

# 下载源码
wget http://nginx.org/download/nginx-1.20.2.tar.gz
tar -zxvf nginx-1.20.2.tar.gz
cd nginx-1.20.2# 配置编译选项
./configure --prefix=/etc/nginx \--sbin-path=/usr/sbin/nginx \--conf-path=/etc/nginx/nginx.conf \--with-http_ssl_module \--with-http_v2_module# 编译安装
make && make install

Docker安装

# 拉取nginx镜像
docker pull nginx# 运行nginx容器
docker run -d -p 80:80 --name mynginx nginx# 使用自定义配置
docker run -d -p 80:80 \-v /path/to/nginx.conf:/etc/nginx/nginx.conf \--name mynginx nginx

验证安装

# 检查nginx版本
nginx -v# 检查配置文件语法
nginx -t# 在浏览器访问
http://your-server-ip
# 应该看到"Welcome to nginx!"页面

Nginx基本概念

1. 进程模型

Master进程和Worker进程
Nginx进程架构:Master进程 (老板)
├── Worker进程1 (员工1) - 处理客户请求
├── Worker进程2 (员工2) - 处理客户请求  
├── Worker进程3 (员工3) - 处理客户请求
└── Worker进程4 (员工4) - 处理客户请求Master进程职责:
- 读取配置文件
- 管理Worker进程
- 处理信号Worker进程职责:
- 处理客户端请求
- 执行具体业务逻辑
查看进程
# 查看nginx进程
ps aux | grep nginx# 输出示例:
# root      1234  0.0  0.1  nginx: master process
# www-data  1235  0.0  0.2  nginx: worker process
# www-data  1236  0.0  0.2  nginx: worker process

2. 事件驱动模型

传统模型 vs Nginx模型
传统模型(Apache prefork):
一个请求 → 一个进程/线程
100个并发 → 100个进程/线程Nginx事件驱动模型:
多个请求 → 一个Worker进程
10000个并发 → 几个Worker进程比喻:
传统模型:银行每个客户配一个专门柜员
Nginx模型:银行几个柜员,客户排队,谁准备好了就服务谁

3. 模块化架构

核心模块
Nginx模块就像汽车的不同部件:核心模块 (引擎):
- 基本功能,必须有标准HTTP模块 (基础配置):
- http_core_module: HTTP核心功能
- http_access_module: 访问控制
- http_gzip_module: 压缩功能可选模块 (高级配置):
- http_ssl_module: HTTPS支持
- http_realip_module: 真实IP获取
- http_stub_status_module: 状态监控

4. 配置块概念

配置层次结构
nginx.conf 配置文件结构:全局块 (影响整个nginx)
├── events块 (连接处理)
└── http块 (HTTP相关)├── upstream块 (上游服务器)├── server块 (虚拟主机)│   ├── location块 (URL匹配)│   ├── location块│   └── location块└── server块├── location块└── location块

配置文件详解

配置文件位置

# 主配置文件
/etc/nginx/nginx.conf# 站点配置目录
/etc/nginx/sites-available/  # 可用站点
/etc/nginx/sites-enabled/    # 启用站点# 配置片段目录
/etc/nginx/conf.d/# 日志目录
/var/log/nginx/# 网站根目录
/var/www/html/

基本配置文件结构

# 全局配置块
user nginx;                          # 运行用户
worker_processes auto;               # Worker进程数量
error_log /var/log/nginx/error.log;  # 错误日志位置
pid /run/nginx.pid;                  # PID文件位置# 事件块
events {worker_connections 1024;         # 每个Worker最大连接数use epoll;                       # 事件驱动模型
}# HTTP块
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;# 包含其他配置文件include /etc/nginx/conf.d/*.conf;include /etc/nginx/sites-enabled/*;
}

详细配置说明

全局配置详解
# 运行nginx的用户和组
user nginx nginx;# Worker进程数量设置
worker_processes auto;              # auto表示自动检测CPU核心数
# worker_processes 4;              # 也可以手动指定数量# Worker进程优先级设置 (-20到20,数值越小优先级越高)
worker_priority -10;# Worker进程可以打开的最大文件数
worker_rlimit_nofile 65535;# 错误日志级别:debug, info, notice, warn, error, crit
error_log /var/log/nginx/error.log warn;# 进程PID文件
pid /var/run/nginx.pid;
事件配置详解
events {# 每个Worker进程的最大连接数worker_connections 1024;# 网络I/O模型use epoll;                      # Linux下推荐epoll# use kqueue;                   # FreeBSD下推荐kqueue# 是否允许一个Worker进程同时接受多个新连接multi_accept on;# 是否接受请求时使用mutex锁accept_mutex off;
}
HTTP配置详解
http {# MIME类型配置include       /etc/nginx/mime.types;default_type  application/octet-stream;# 字符集charset utf-8;# 是否在Server头中显示nginx版本server_tokens off;# 日志格式定义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 detailed '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for" ''$request_time $upstream_response_time';# 访问日志access_log /var/log/nginx/access.log main;# 文件传输优化sendfile on;                    # 启用高效文件传输tcp_nopush on;                  # 优化TCP传输tcp_nodelay on;                 # 禁用Nagle算法# 连接超时设置keepalive_timeout 65;           # 保持连接超时时间keepalive_requests 100;         # 单个连接最大请求数# 客户端请求限制client_max_body_size 100m;      # 客户端请求体最大大小client_body_timeout 60;         # 客户端请求体超时client_header_timeout 60;       # 客户端请求头超时# 压缩配置gzip on;                        # 启用gzip压缩gzip_vary on;                   # 启用vary头gzip_min_length 1000;           # 最小压缩文件大小gzip_comp_level 6;              # 压缩级别(1-9)gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}

静态文件服务

基本静态文件服务

简单网站配置
server {listen 80;                      # 监听端口server_name example.com;        # 域名root /var/www/html;             # 网站根目录index index.html index.htm;     # 默认文件# 处理所有请求location / {try_files $uri $uri/ =404;  # 尝试文件,然后目录,最后404}
}
完整静态网站配置
server {listen 80;server_name www.example.com example.com;root /var/www/example.com;index index.html index.htm;# 访问日志access_log /var/log/nginx/example.access.log;error_log /var/log/nginx/example.error.log;# 主页面处理location / {try_files $uri $uri/ =404;}# 静态资源缓存location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {expires 1y;                 # 缓存1年add_header Cache-Control "public, immutable";access_log off;             # 不记录静态资源访问日志}# 字体文件处理location ~* \.(ttf|ttc|otf|eot|woff|woff2)$ {add_header Access-Control-Allow-Origin "*";expires 1y;access_log off;}# 禁止访问隐藏文件location ~ /\. {deny all;access_log off;log_not_found off;}# 禁止访问备份文件location ~ ~$ {deny all;access_log off;log_not_found off;}
}

目录浏览配置

启用目录浏览
server {listen 80;server_name files.example.com;root /var/www/files;location / {autoindex on;               # 启用目录浏览autoindex_exact_size off;   # 显示文件大小格式化autoindex_localtime on;     # 显示本地时间autoindex_format html;      # 格式:html, xml, json, jsonp}# 自定义目录页面样式location = /autoindex.css {add_header Content-Type text/css;return 200 "body { font-family: Arial; margin: 40px; }h1 { color: #333; }a { text-decoration: none; }a:hover { text-decoration: underline; }";}
}

多媒体文件处理

视频文件流媒体
server {listen 80;server_name media.example.com;root /var/www/media;# 视频文件处理location ~* \.(mp4|avi|flv|wmv|mkv)$ {mp4;                        # 启用MP4模块mp4_buffer_size 1m;mp4_max_buffer_size 5m;# 允许HTTP范围请求(支持断点续传)add_header Accept-Ranges bytes;# 缓存设置expires 7d;add_header Cache-Control "public, no-transform";}# 音频文件处理location ~* \.(mp3|wav|ogg|aac)$ {add_header Accept-Ranges bytes;expires 7d;}# 图片文件处理location ~* \.(jpg|jpeg|png|gif|webp)$ {# 图片压缩(需要image_filter模块)image_filter resize 800 600;image_filter_jpeg_quality 85;expires 30d;add_header Cache-Control "public, immutable";}
}

文件下载服务

文件下载配置
server {listen 80;server_name download.example.com;root /var/www/downloads;# 普通下载location /files/ {alias /var/www/downloads/;# 设置下载头add_hea
http://www.xdnf.cn/news/989101.html

相关文章:

  • xilinx的GT配置说明(一)
  • Barcode解码 一维码、二维码识别 物流单号识别
  • Flink 系列之二十六 - Flink SQL - 中间算子:普通聚合
  • QDockWidget
  • Spring Data MongoDB 技术指南
  • JS开发node包并发布流程
  • 基于地形数据计算山体阴影
  • 【指针】(适合考研、专升本)
  • MySQL中外键约束详解 外键在表关系维护中的作用
  • vue定义的组件在外部引入时的问题
  • centos7 安装 zabbix6 -proxy
  • 51la统计怎么用及悟空统计的独特优势
  • C#winform画图代码记录
  • Java八股文——Spring「SpringCloud 篇」
  • 西安java面试总结1
  • 亚马逊Woot黑五策略,快速提升亚马逊业绩
  • Docker三大核心组件详解:镜像、容器、仓库的协作关系
  • 模拟IC设计提高系列5-温度角与蒙特卡洛仿真
  • 基于GA遗传优化的PID控制器最优控制参数整定matlab仿真
  • OpenLayers 加载Geoserver WMTS服务
  • 进程的信号掩码,信号集,sigprocmask函数
  • QMultiMapQHashQList使用区别
  • 中学教资考试面试回忆
  • 学车笔记 变挡
  • 图数据库的理解
  • Python打卡第51天
  • n8n部署步骤
  • AI Engine Kernel and Graph Programming--知识分享9
  • PostgreSQL --数据库操作
  • libyuv的三种缩放模式