前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【随手记】Nginx?开卷!

【随手记】Nginx?开卷!

作者头像
客怎眠qvq
发布2024-08-07 14:02:39
1040
发布2024-08-07 14:02:39
举报
文章被收录于专栏:某菜鸟の小屋

【随手记】Nginx?开卷!

客怎眠qvq2024-04-262024-07-26

🍭 前言

老大安排的,被迫营业,去给同事讲 Nginx。别急着走嘛🫠文章中的几个例子很简单的。

ℹ️ 基本介绍(可跳过,但强烈建议看看)

Nginx 是一个高性能的 HTTP 服务器和反向代理,它以其稳定性、丰富的功能集、简单的配置和低资源消耗而闻名。Nginx主要用来处理HTTP请求,提供负载均衡、静态内容服务、反向代理等功能。

正向代理:居家办公用过公司的内网VPN吧,你所有的请求在发送前,被代理成了内网的IP去获取内网的资源,如数据库、私有代码仓库等。

反向代理:业务中经常用到,所有前端的请求被发送到同一个端口(80),通过Nginx监听转发到相应的前端、后端上。比如 前端Vue项目启动在8080上,但它不会被直接访问,只会从80端口被转发到8080,用户浏览器显示的站点还是原站点,只是内容变成了8080的页面。

🚑 热备(backup):服务器界的“备胎”,一台服务器故障,另一台马上顶上。 🎭 轮询:请求按顺序分发到服务器,雨露均沾。 ⚖️ 加权轮询(weight):根据配置的权重大小而分发给不同服务器不同数量的请求,可根据服务器配置调整对应权重,让强壮的服务器多干点活,降低其他服务器负载。 🔄 ip_hash:让相同IP的客户端总是访问同一个服务器,保持会话一致性。

🔑 参数配置

Nginx 的主配置文件通常位于以下位置📍:

  • linux系统/etc/nginx/nginx.conf
  • Windows系统:随Nginx安装路径而变化,在安装目录下的 conf\nginx.conf 中,如果你安装在 D:/program/nginx-1.22,那么配置文件就在 D:/program/nginx-1.22/conf/nginx.conf

其配置结构如下:

代码语言:javascript
复制
-——全局块
|
|——event块
|
-——http块
  |
  -——server块
      |
      -——location块

Nginx默认配置及说明如下:

代码语言:javascript
复制
#
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #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;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #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;
    #    }
    #}
}
代码语言:javascript
复制
########### 每个指令必须有分号结束。#################
#user administrator administrators;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #允许生成的进程数,默认为1
#pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址
error_log log/error.log debug;  #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {
    accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on
    multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
    #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大连接数,默认为512
}
http {
    include       mime.types;   #文件扩展名与文件类型映射表
    default_type  application/octet-stream; #默认文件类型,默认为text/plain
    #access_log off; #取消服务日志    
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
    access_log log/access.log myFormat;  #combined为日志格式的默认值
    sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
    sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
    keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。

    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #热备
    }
    error_page 404 https://www.baidu.com; #错误页
    server {
        keepalive_requests 120; #单连接请求上限次数。
        listen       4545;   #监听端口
        server_name  127.0.0.1;   #监听地址       
        location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
           #root path;  #根目录
           #index vv.txt;  #设置默认页
           proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
           deny 127.0.0.1;  #拒绝的ip
           allow 172.18.5.54; #允许的ip           
        } 
    }
}

🌰 案例教学

🔝 location 匹配优先级(不讲后缀匹配)

1、精准匹配 (优先级最高)

代码语言:javascript
复制
#将所有对根域名的请求都重定向到统一认证的地址
location = / {
  rewrite ^/(.*)$ https://iam.test.com;
}

2、正则前缀匹配(匹配到后,停止搜索)

代码语言:javascript
复制
#所有匹配到 /images/ 请求都会转发到静态资源服务器的images路径下
location ^~ /images/ {
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header Host $proxy_host;
  proxy_pass http://static_server/images;
}

3、不区分大小写、区分大小写的前缀匹配(~* 优先级高于 ~,但仍会向下搜索)

代码语言:javascript
复制
location ~* /upload {
  // 不区分大小写
}

location ~ /Upload {
  // 区分大小写 且优先级低于 ~*
}

location ~* /upload/images {
  // 优先级相同,取规则最准确的(最长的)
}

4、前缀匹配(最常用)

代码语言:javascript
复制
location /api/weekly {
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header Host $proxy_host;
  proxy_pass http://backend_server/weekly;
}

5、通用匹配(任何未匹配到的请求都会走这条配置,由于与1的精准匹配重叠,所以不会生效)

代码语言:javascript
复制
location / {
  # proxy_http_version 1.1;
  proxy_set_header X-Real-IP $remote_addr;
  client_max_body_size 20M;
  client_body_buffer_size 20M;
  proxy_set_header Host test.com;
  proxy_pass http://dev_ui;
}

优先级及匹配字符长度相同的情况下,按location块先后顺序决定优先级

➡️ root路径映射

root被用来统一查找文件时的根目录,路径映射规则简单直观。它可以在http、server、location中定义,可单独使用。路径映射的规则可以直接参照linux命令行。

  • 作用:定义全局的根目录,可被子模块中的root配置覆盖。
  • 位置:可以在http、server、location中定义,可单独使用。
  • 映射规则:可以相对路径、可以是绝对路径。
代码语言:javascript
复制
# 通用匹配只能有一条,多条nginx -t 检查会报错
# 换句话说,配置中只能有一个 location / {} 块
# 下列配置仅针对 精准匹配未影响通用匹配的情况下,且只能有一份
location / {
  # 访问test.com显示/usr/local/html/absolute下的index.htm(l)页面
  root /usr/local/html/absolute;
  index index.html index.htm;
}

location / {
  # 访问test.com显示D:/usr/local/html/test下的index.htm(l)页面
  root   D:/usr/local/html/test;
  index  index.html index.htm;
}

location / {
  # 访问test.com显示 nginx 安装目录下的 html/relative/index.htm(l) 页面
  root   html/relative;
  index  index.html index.htm;
}

🔍 root 与 alias 的区别

  1. 路径 root的处理结果:root路径+location路径 alias的处理结果:使用alias路径替换location路径 alias是一个目录别名的定义,root则是最上层目录的定义
  2. 作用域 alias只能作用在location中;而root可以存在server、http和location中,且会影响其他块。
  3. 语法格式 alias后面必须要用 “/” 结束,不然会被认为是个文件,而找不到对应的目录;而root则对 “/” 可有可无。 alias不支持直接使用正则,但可以获取location匹配的参数,且必须使用。 在同一个 location 块中,不能同时使用 root 和 alias。

建议在server块中定义全局的根目录,在location块中根据需要配置alias。如果需要正则匹配实现alias的效果,就用到了rewrite。

↩️ rewrite重写

rewrite 指令是 Nginx 中的瑞士军刀,它可以用来重写请求URI,实现各种灵活的跳转和路由。

代码语言:javascript
复制
 rewrite    <regex>    <replacement>    [flag];
关键字      正则        替代内容          flag标记(可为空)
代码语言:javascript
复制
location /testrewrite {
  # 使用rewrite指令重写请求URI
  rewrite ^/(.*)$ https://baidu.com permanent;
  
  # 重写后的请求将被转发到baidu.com
}

location /testrewrite2/ {
    # 使用rewrite指令重写请求URI
    # 捕获 /testrewrite2/ 后面的所有内容作为 $1
    rewrite ^/testrewrite2/(.*)$ https://cn.bing.com/search?q=$1 permanent;
    # 转发到重写后的 URI
    #proxy_pass https://cn.bing.com;
}

🔗 参考链接

引用站外地址

Nginx配置详解

菜鸟教程

引用站外地址

Nginx系列:root与alias指令用法的区别

腾讯云社区

引用站外地址

正向代理、反向代理及负载均衡

CSDN

引用站外地址

Nginx官方文档

Nginx官网

引用站外地址

Nginx做负载均衡并显示转发日志

博客园

引用站外地址

Nginx 反向代理与负载均衡详解

菜鸟教程

引用站外地址

Nginx location匹配规则及优先级

CSDN

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-04-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 【随手记】Nginx?开卷!
    • 🍭 前言
      • ℹ️ 基本介绍(可跳过,但强烈建议看看)
        • 🔑 参数配置
          • 🌰 案例教学
            • 🔝 location 匹配优先级(不讲后缀匹配)
            • ➡️ root路径映射
            • 🔍 root 与 alias 的区别
            • ↩️ rewrite重写
          • 🔗 参考链接
          相关产品与服务
          负载均衡
          负载均衡(Cloud Load Balancer,CLB)提供安全快捷的流量分发服务,访问流量经由 CLB 可以自动分配到云中的多台后端服务器上,扩展系统的服务能力并消除单点故障。负载均衡支持亿级连接和千万级并发,可轻松应对大流量访问,满足业务需求。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档