Nginx基本概括

基础总结

 反向代理
 挡在服务器前面统一迎客,保护后端,隐藏细节
 ​
 Upstream
 定义后端服务器池,方便横向轻松扩展
 ​
 负载均衡
 通过轮询、权重、IPHash,分流更加合理
 ​
 动静分离
 Nginx自己处理静态,后端专心处理动态
 ​
 健康检查与容错
 自动隔离故障服务器,保证服务高可用
 ​
 nginx.conf配置
 大括号大统领下,使用-sreload瞬间生效

常用指令

 nginx -t                    # 检查配置文件语法是否正确
 nginx -s reload             # 热重载配置,无感应用新配置
 tail -f access.log          # 实时查看访问日志(PV/UV)
 tail -f error.log           # 查看报错(定位502/504 必备)

Nginx目录结构

 /usr/local/nginx/
 ├── sbin/
 │   └── nginx              # 二进制执行文件
 ├── conf/
 │   └── nginx.conf         # 主配置文件
 ├── logs/
 │   └── access.log         # 访问与错误日志
 └── html/
     └── 50x.html           # 默认静态资源

Nginx 配置更新

 # 第一步:检查语法
 nginx -t
 ​
 # 第二步:平滑重载
 nginx -s reload
 ​
 # 第三步:观察错误日志
 tail -f /var/log/nginx/error.log

Nginx 生命周期管理

 nginx                # 启动
 nginx -s reload      # 重新加载配置
 nginx -s quit        # 优雅停止
 nginx -s stop        # 强制停止
 nginx -t             # 只检查配置语法
 ​
 Nginx 生命周期
 │
 ├── 🔄 启动阶段
 │   └── nginx
 │       ├── 读取配置文件 (/usr/local/nginx/conf/nginx.conf)
 │       ├── Master 进程启动(以 root 权限)
 │       ├── Worker 进程启动(以普通用户权限)
 │       └── 开始监听端口,处理请求
 │
 ├── 🔧 运行维护阶段
 │   ├── nginx -s reload
 │   │   ├── 检查配置文件语法(内部自动执行 nginx -t)
 │   │   ├── Master 启动新 Worker(加载新配置)
 │   │   └── 旧 Worker 处理完当前请求后退出 → 平滑切换
 │   │
 │   └── nginx -t
 │       └── 单独检查配置文件语法(不执行重载)
 │
 └── 🛑 停止阶段
     ├── nginx -s quit(优雅停止)
     │   ├── Master 停止接收新连接
     │   ├── Worker 处理完当前请求后退出
     │   └── 所有连接关闭后,Master 退出
     │
     └── nginx -s stop(强制停止)
         ├── Master 发送 TERM 信号
         ├── 立即终止所有进程
         └── 正在处理的请求可能中断

配置文件注释解释

 # 全局配置
 # 指定运行nginx工作进程的用户,默认nobody(此处被注释,使用默认)
 #user  nobody;
 ​
 # 默认进程数,建议和核心CPU保持一致【auto自动 用几个才会开几个不会直接全开】
 # 建议设为CPU核心数,此处为1
 worker_processes  1;
 ​
 # 错误日志文件路径(被注释)
 #error_log  logs/error.log;
 # 错误日志级别设为notice(被注释)
 #error_log  logs/error.log  notice;
 # 错误日志级别设为info(被注释)
 #error_log  logs/error.log  info;
 ​
 # 存储nginx主进程PID的文件路径(被注释)
 #pid        logs/nginx.pid;
 ​
 ​
 events {
     # 每个工作进程允许的最大并发连接数
     worker_connections  1024;
 }
 ​
 # http(超文本传输协议)Nginx就是一种Web服务,http服务端,客户端(浏览器)
 http {
     # 引入mime.types文件,定义文件扩展名与MIME类型的映射
     include       mime.types;
     # 默认MIME类型,未匹配时按二进制流处理
     default_type  application/octet-stream;
 ​
     # 定义名为"main"的日志格式(被注释)
     #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高效传输静态文件,减少CPU开销
     sendfile        on;
     # 启用TCP_NOPUSH/CORK,与sendfile配合优化网络包发送(被注释)
     #tcp_nopush     on;
 ​
     # 长连接超时时间,0为禁用(被注释)
     #keepalive_timeout  0;
     # 长连接超时时间,65秒
     keepalive_timeout  65;
 ​
     # 启用gzip压缩传输(被注释)
     #gzip  on;
 ​
     # 服务:一个server就是一个“网站”
     server {
         # http默认使用80端口,http默认使用443端口
         listen       80;
         # 服务器域名,匹配访问的域名
         server_name  localhost;
 ​
         # 该虚拟主机的访问日志(被注释)
         #access_log  logs/host.access.log  main;
 ​
         location / {
             # 网站根目录,相对nginx安装路径
             root   html;
             # 默认索引文件,按顺序查找
             index  index.html index.htm;
         }
         
          location /app {
             # root 指定网站的“根”路径,“/” +app
             # root   /data/html; # /app -> /data/html/app
             # alias 替换URL中的路径替换为系统中的路径
             # /app -> /data/heml
             index  index.html;
         }        
 ​
         # 自定义404错误页面(被注释)
         #error_page  404              /404.html;
 ​
         # 服务器错误重定向到静态页面 /50x.html
         error_page   500 502 503 504  /50x.html;
         # 匹配50x错误页面的精确位置
         location = /50x.html {
             # 50x.html所在根目录
             root   html;
         }
 ​
         # 将PHP脚本代理到监听127.0.0.1:80的Apache(被注释)
         #location ~ \.php$ {
         #    proxy_pass   http://127.0.0.1;
         #}
 ​
         # 将PHP脚本传递给127.0.0.1:9000的FastCGI服务器处理(被注释)
         #location ~ \.php$ {
         #    root           html;
         #    fastcgi_pass   127.0.0.1:9000;
         #    fastcgi_index  index.php;
         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
         #    include        fastcgi_params;
         #}
 ​
         # 拒绝访问.htaccess等隐藏文件(被注释)
         #location ~ /\.ht {
         #    deny  all;
         #}
     }
 ​
 ​
     # 另一个虚拟主机配置示例,基于IP、域名、端口的混合方式(被注释)
     #server {
     #    listen       8000;
     #    listen       somename:8080;
     #    server_name  somename  alias  another.alias;
 ​
     #    location / {
     #        root   html;
     #        index  index.html index.htm;
     #    }
     #}
 ​
 ​
     # HTTPS服务器配置示例(被注释)
     #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;
 ​
     #    ssl_ciphers  HIGH:!aNULL:!MD5;
     #    ssl_prefer_server_ciphers  on;
 ​
     #    location / {
     #        root   html;
     #        index  index.html index.htm;
     #    }
     #}
 ​
 }
 # worker连接上限设置
 ​
 events {
     use epoll;                  # Linux使用epoll事件模型
     worker_connections 65535;   # 单个worker连接上限
     multi_accept on;            # 一次性接收多个新连接
 }

网站显示内容

在配置文件里新加的app里的网址内的显示内容【app是目录名字可修改 如修改记得跟配置文件里的名字一致】

 # 比如路径在 /data/html/app 如果路径不存在需要创建
 # 创建路径
 mkdir -p /data/html/app
 ​
 # 切换目录
 cd /data/html/app
 ​
 # 编辑网页内容(在里面添加)
 vim index.html
 ​
 # 相对应的配置文件里面也需要添加内容
 # 路径:cd /usr/local/nginx/conf/nginx.conf
 # 添加以下内容
 location /app {
     root /data/html;
     index index.html;
 } 
    
    或
    
 location /app {
     alias /data/html;      # 访问 /app 直接对应 /data/html
     index index.html;
 } 
 ​
 ## 注释:
 使用 root:查找 /data/html/app(这是个文件,不是目录)
 使用 alias:查找 /data/html(这是个目录),然后返回 /data/html/index.html
 ​
 # 修改完配置文件后刷新配置
 cd /usr/local/nginx/sbin
 ./nginx -s reload
 ​
 # 在浏览器查看
 192.168.8.5/app

配置文件的格式

 # /etc/nginx/nginx.conf — 主配置文件
 ​
 # ——— 全局块 ———
 user  nginx;                          # 运行用户nobody
 worker_processes  auto;               # Worker 进程数(建议 auto = CPU 核心数)
 error_log  /var/log/nginx/error.log notice;  # 错误日志
 pid        /var/run/nginx.pid;        # PID 文件
 ​
 # ——— events 块(网络连接) ———
 events {
     worker_connections  1024;          # 单个 Worker 最大连接数
     use  epoll;                        # 事件驱动模型(Linux 最佳)
     multi_accept  on;                  # 一次接受多个新连接
 }
 ​
 # ——— http 块(HTTP 协议配置) ———
 http {
     include       /etc/nginx/mime.types;          # MIME 类型
     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;             # 长连接超时
     gzip  on;                          # 开启压缩
 ​
     # ——— server 块(虚拟主机) ———
     server {
         listen       80;               # 监听端口
         server_name  localhost;        # 域名
 ​
         # ——— location 块(URI 匹配) ———
         location / {
             root   /usr/share/nginx/html;   # 网站根目录
             index  index.html index.htm;    # 默认首页
         }
 ​
         error_page   500 502 503 504  /50x.html;   # 错误页
     }
 }

常用命令速查

 # ——— 路径配置 ———
 root   /var/www/html;           # 网站根目录
 alias  /path/to/static/;        # location 别名
 ​
 # ——— 索引文件 ———
 index  index.html index.htm index.php;
 ​
 # ——— 请求头 ———
 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_pass http://backend;
 proxy_pass http://127.0.0.1:8080;
 ​
 # ——— 重定向 ———
 rewrite ^/old/(.*)$ /new/$1 permanent;    # 301 重定向
 return 301 https://$host$request_uri;     # HTTP → HTTPS

负载均衡算法选择

 轮询
 机器性能相近的普通 Web 服务
 ​
 权重
 机器性能不一致
 ​
 ip_hash
 简单会话保持,不用改代码
 ​
 least_conn
 长连接、请求耗时差异大
 ​
 一致性Hash
 缓存类场景,节点增减影响要小
 ​
 # 总结回顾
 - 算法选择:按场景选,没有万能算法
 - 会话保持:优先考虑 Session 集中存储,而不是绑定某台机器
 ​
 weight 和机器性能不匹配
 你给某台机器设置了很高的权重(希望它多干活),但这台机器实际配置很低。结果流量全涌过来,小机器被压垮,大机器反而闲着。
 ​
 ip_hash 遇到大 NAT 出口
 ip_hash 本意是把同一个用户的请求始终分到同一台机器。但如果公司/学校几万人共用一个出口 IP,负载均衡会误以为这是“同一个用户”,把所有人的请求都甩给同一台机器,导致它过载。
 ​
 只用被动健康检查
 被动检查是“等用户访问失败了才发现机器挂了”。这意味着第一批访问故障机器的用户,一定会遇到超时或报错,体验很差。
 ​
 Session 存在本地内存
 用户登录信息只存到了某台机器的内存里。如果这台机器重启或扩容新机器,用户再次请求被分到别的机器时,内存里没有他的 Session,就会被强制踢下线。
 ​
 简单总结:权重别乱设、ip_hash 在大网络下会失灵、健康检查要主动做、Session 要集中存放(比如 Redis)。

常见的日志变量

  • $remote_addr, $http_x_forwarded_for 记录客户端IP地址

  • $remote_user记录客户端用户名称

  • $request记录请求的URL和HTTP协议(GET,POST,DEL,等)

  • $status记录请求状态

  • $body_bytes_sent发送给客户端的字节数,不包括响应头的大小;该变量与Apache模块mod_log_config里的“%B”参数兼容。

  • $bytes_sent发送给客户端的总字节数。

  • $connection连接的序列号。

  • $connection_requests 当前通过一个连接获得的请求数量。

  • $msec 日志写入时间。单位为秒,精度是毫秒。

  • $pipe如果请求是通过HTTP流水线(pipelined)发送,pipe值为“p”,否则为“.”。

  • $http_referer 记录从哪个页面链接访问过来的

  • $http_user_agent记录客户端浏览器相关信息

  • $request_length请求的长度(包括请求行,请求头和请求正文)。

  • $request_time 请求处理时间,单位为秒,精度毫秒;从读入客户端的第一个字节开始,直到把最后一个字符发送给客户端后进行日志写入为止。

  • $time_iso8601 ISO8601标准格式下的本地时间。

  • $time_local通用日志格式下的本地时间。