Nginx Simple Getting Started Guide

foreword

Boss:CDN + Nginx 怎么玩的你知道不?

I:此处省略一亿个点 ... ☺

Boss:简单来说,前端项目通过打包构建工具生成的最终产物,会先上传到【对象存储】中(例如:阿里云 OSS、腾讯云 COS);【对象存储】中的静态资源通过接入 CDN 服务,再由 CDN 进行加速处理,然后分发到用户客户端;但最前置会有个 Nginx 服务,它配置反向代理指向 CDN 地址,然后 CDN 去【对象存储】中拉数据

Boss:这是最常用的,前端资源打包后 PUSH 到【对象存储】时,就会去触发刷新 CDN

I:此处赞一手 ☺

So I thought about it and started to learn Nginx -related content, so I got this article.

Nginx basic content

what is it?

Nginx is a lightweight HTTP server that uses event-driven, asynchronous non-blocking processing. It has excellent IO performance and is often used in HTTP servers (including dynamic and static separation) , forward proxy , reverse proxy , and load balancing . and many more.

Nginx and Node.js are similar in many aspects, such as HTTP servers, event-driven, asynchronous non-blocking, etc., and the functions of Nginx can also be implemented using Node.js , but their usage scenarios are different. , Nginx is good at processing low-level server-side resources (static resource processing forwarding, reverse proxy, load balancing, etc.), Node.js is better at processing upper-layer specific business logic.

Download and launch

download

You can directly visit the Nginx official website to download the corresponding compressed package:

  • Method 1 : You can download directly from various mainline version or stable version on the main page
  • 方式二:可通过右侧导航的 download 选项进行下载,一般下载 稳定版本

解压

将对应的 .zip 压缩文件解压并存放到合适的磁盘目录即可.

启动服务

进入到对应的 Nginx 目录,双击执行 nginx.exe 或者在命令行中通过 start nginx 启动服务,启动后会有一闪而过的弹窗,这就代表启动成功了,此时通过浏览器访问 http://localhost:

.conf 配置文件简介

Nginx 的配置文件位置为 /nginx-xxx/conf/nginx.conf ,可以查看或添加和修改配置文件:

配置文件大致结构可以分为:

Nginx 实战

Http 服务

这里直接使用一个简单的 vite-vue3 项目来演示 nginx 部署静态资源的过程:

  • 准备一个 demo 项目,正常通过脚手架的 web 服务进行访问,如下:

  • demo 项目进行打包得到构建的产物 dist 目录

  • dist 目录更名为 vite-vue3 并放在 D:\nginx-1.22.0\html 目录下

    image.png

  • 修改 D:\nginx-1.22.0\conf\nginx.conf 配置文件,对应配置如下,比较简单:

    image.png

  • 通过访问 http://localhost/vite-vue3/ 部署好的页面,如下所示:

以上只是简单的配置静态资源服务,还可以自行设置缓存、配置代理、配置多个 server 内容等等

正向代理

正向代理的代理对象是客户端,正向代理就是代理服务器替客户端去访问目标服务器.

这里举一个简单的 跨域 的例子,然后通过 nginx 去配置代理,解决对应的跨域问题.

  • 后端服务部分 基于 express 来启动模拟一个业务处理服务器,代码如下:

    const express = require('express');
    
    const app = express();
    
    app.get('/',(req, res,next)=>{
        res.end('<h1>hello world!!!</h1>');
    });
    
    app.get('/getBooks',(req, res,next)=>{
        setTimeout(()=>{
            const data = new Array(5).fill(1).map((v,i) => {
                return {id: i + 1, name: `test title ${i+1}`, price: i + 100 }
            });
            res.json(data);
        }, 2000);
    });
    
    app.listen(8009, (err) => {
        if(err) {
            console.log("server run with error!!");
            return
        }
        console.log("server is runing at:http://10.98.214.68:8009");
    });
    
  • 前端页面部分 仍然使用上面的 vite-vue 项目,只不过会在 App.vue 组件的 onMounted 生命周期钩子中通过 fectch 请求 http://10.98.214.68:8009/getBooks 接口,结果如预期发生跨域:

    image.png

  • 通过 nginx 配置代理并重新启动,具体如下:

    // 方式一
    location /getBooks {
            proxy_buffer_size 64k;
            proxy_buffers  32 32k;
            proxy_busy_buffers_size 128k;
    
            add_header Access-Control-Allow-Origin '*' always;
            add_header Access-Control-Allow-Headers "Accept,Accept-Encoding,Accept-Language,Connection,Content-Length,Content-Type,Host,Origin,Referer,User-Agent";
            add_header Access-Control-Allow-Methods "GET, POST, PUT, OPTIONS";
            add_header Access-Control-Allow-Credentials true;
    
            proxy_pass  http://10.98.214.68:8009/getBooks;
    }
    
  • App.vue 中通过请求 nginx 代理服务器,代码如下:

    onMounted(() => {
      console.log('发送请求')
      fetch('http://10.98.214.68:80/getBooks')
        .then((res) => {
          return res.json()
        })
          .then((res) => {
          console.log('接收到响应结果:', res)
        })
        .catch((err) => {
          console.error('请求异常:', err)
        })
    })
    

    image.png

反向代理

反向代理指代理后端服务器响应客户端请求的一个中介服务器,代理的对象是服务端.

这里举一个通过页面访问 /abc//abc/ 是,能够分别访问不同服务器的例子,如下:

  • 启动两个 node 服务模拟不同的服务器,如下:

    // server-abc.js
    const express = require('express');
    const app = express();
    
    app.get('/',(req, res,next)=>{
       res.end(`<h1>hello world 8001!!! <small>this page real url is http://127.0.0.1:8001</small></h1>`);
    });
    
    app.listen(8001, (err) => {
       if(err) {
           console.log("server run with error!!");
           return
       }
       console.log("server is runing at:http://127.0.0.1:8001");
    });
    
    // server-xyz.js
    const express = require('express');
    const app = express();
    
    app.get('/',(req, res,next)=>{
       res.end(`<h1>hello world 8002!!! <small>this page real url is http://127.0.0.1:8002</small></h1>`);
    });
    
    app.listen(8002, (err) => {
       if(err) {
           console.log("server run with error!!");
           return
       }
       console.log("server is runing at:http://127.0.0.1:8002");
    });
    
  • 配置 nginx 代理服务器,实现通过访问 /abc/ 能跳转到 http://127.0.0.1:8001,通过访问 /abc/ 能跳转到 http://127.0.0.1:8002,具体配置如下: ```js location /abc/ {
    proxy_pass http://127.0.0.1:8001/;
    }

    location /xyz/ {  
       proxy_pass http://127.0.0.1:8002/;         
    } 
    ```
    
  • 重启 nginx 并访问,如下:

负载均衡

负载均衡其意思就是分摊到多个操作单元上进行执行,例如 Web 服务器、FTP 服务器、企业关键应用服务器和其它关键任务服务器等,从而共同完成工作任务.

简单说就是当有 2 台或以上服务器时,根据规则随机的将请求分发到指定的服务器上处理,负载均衡配置一般都需要同时配置反向代理,通过反向代理跳转到负载均衡.

  • 核心配置如下:
upstream myserver {   
  server 127.0.0.1:8001;
  server 127.0.0.1:8002;
}

server {
    listen       80;
    server_name  localhost;
    
    ...

    location / {
        root   html;
        index  index.html index.htm;
        proxy_set_header Host $host:$server_port;
        proxy_pass  http://myserver;  #请求转向 myserver 定义的服务器列表      
    }
    
    ...
 }

参考资源

我正在参与掘金技术社区创作者签约计划招募活动,点击链接报名投稿

Guess you like

Origin juejin.im/post/7117882024651653127
Recommended