Front-end Engineering - Manage your front-end resources with Nginx

foreword

In front-end project development, we can start the service of devservermanaging static resources, but to ensure stability after the release online, we generally choose a high-performance + stable static server to manage front-end resources.

As a key part of front-end engineering, let's learn the common usage of Nginx in this article.

Nginx  (engine x) is a high performance HTTP and reverse proxy web server that also provides IMAP/POP3/SMTP services.

regular use

The installation process of Nginx is omitted. After all, it is a basic operation, and WIndows is installed with one click.

Remember a few common commands first, we will use them continuously later:

  • start nginx: start
  • nginx nginx -s reload: Reload takes effect after modifying the configuration
  • nginx -s stop: fast stop
  • nginx nginx -s quit: stop nginx in a complete and orderly manner

Reverse proxy static resources

For the front end, the most common problem is proxying static resources. We choose the VUE project as a test;

Use Vue CLI to create a demo project, run it and yarn buildoutput following static resources:

image.png

Copy the above generated static resources to any directory (the path is arbitrary, as long as you are happy )

image.png

After modifying the nginx.conffile , start Nginx.

nginx.confThe files are all in the config folder of the Nginx installation directory

http {
    include       mime.types;
    default_type  application/octet-stream;
    keepalive_timeout  65;
    #gzip  on;
    server {
        listen       80;
        location / {
            root   html; // 切换成你的静态资源目录
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
复制代码

image.png

It is also normal to report an error when starting directly. The resource path is wrong. At this time, you can choose to use a relative path or modify the root root path to dist. Here, since we are explaining the Nginx configuration, we choose to change the root root path to dist and then Restart access.

image.png

这个时候大家可以注意到,我们的访问路径已经从 http://127.0.0.1/dist 改变成 http://127.0.0.1/。

image.png

如果你是默认 vue-cli 创建的带路由的项目,那么可以点击一下 About,是可以正常访问,但是刷新之后就会变成 404,这个很正常,默认的路由模式是 hitstory,只需要加上 try file 就可以了。


location / {
    root   html/dist/;
    # index  index.html index.htm;
    try_files $uri $uri/ / ;
}
复制代码

同时,我们在正常使用静态资源的时候也并不是根据 ip 来访问,这里我们可以根据 server_name 配置域名访问。

首先本地 host 配置一个域名 dns 解析到本地:

127.0.0.1 fe.cookieboty.com
复制代码

再在 location 里面添加 server_name 配置,重启 nginx 即可。

 server {
    listen       80;
    server_name fe.cookieboty.com; // 配置监听域名
    location / {
        root   html/dist/;
        try_files $uri $uri/ / ;
    }

    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   html;
    }
}
复制代码

image.png

反向代理接口

反向代理接口也比较简单,经常用碰到的还是跨域的问题,所以才需要代理。

接下来,我们来代理一下掘金的接口看看,正常这种接口再我们的项目中使用是会有跨域的问题。

在 demo 项目中使用 axios 来请求掘金的接口 api.juejin.cn/tag_api/v1/… :

import axios from "axios";

export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  setup() {
    axios
      .get("https://api.juejin.cn/tag_api/v1/query_category_briefs")
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  },
};
复制代码

image.png

虽然没有报跨域的错误,但是直接被 403 拦截了,资源被服务器拦截了。我们用 nginx 的 proxy_pass 来代理这个请求看看。

 server {
    listen       80;
    server_name juejin.cookieboty.com;
    location / {
        proxy_pass  https://api.juejin.cn/;
    }
}
复制代码

浏览器直接访问 juejin.cookieboty.com/tag_api/v1/… 出现如下结果则代表反向代理接口没问题。

image.png

但是在项目中直接运行的时候依然有 403 的错误,如果代理没问题,那就是请求参数有不一致的地方,导致被服务器拒绝,简单对比一下,发现 header 里面的 Orgin 参数有不一致的情况,所以我们修改将转发之后请求头部的 Orgin 设置为 api.juejin.cn 后重启看下效果:

 server {
    listen       80;
    server_name juejin.cookieboty.com;

    location / {
        proxy_set_header Origin https://api.juejin.cn; // 新增 Origin 修改代码
        proxy_pass  https://api.juejin.cn/;
    }
}
复制代码

image.png

完美,demo 项目已经正常代理拿到掘金分类接口的数据了。

似乎没有遇到 cors 跨域的问题,那么后面再说这个好了。

Nginx 参数配置详解

正常根据上述配置,已经可以简单的使用 nginx 的反向代理了,为了后续的更灵活的配置,我们也一起学习一下 Nginx 的参数配置:

nginx.conf 组成

...              #全局块

events {         #events块
   ...
}

http      #http块
{
    ...   #http全局块
    server        #server块
    { 
        ...       #server全局块
        location [PATTERN]   #location块
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局块
}
复制代码

nginx.conf 由以下 5 个模块构成:

  1. 全局块:配置影响 nginx 全局的指令。一般有运行 nginx 服务器的用户组,nginx 进程 pid 存放路径,日志存放路径,配置文件引入,允许生成 worker process 数等。
  2. events:配置影响 nginx 服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。
  3. http:可以嵌套多个 server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type 定义,日志自定义,是否使用 sendfile 传输文件,连接超时时间,单连接请求数等。
  4. server:配置虚拟主机的相关参数,一个 http 中可以有多个 server。
  5. location:配置请求的路由,以及各种页面的处理情况。

对于前端来说一般使用 server + location 两个模块足够了。

变量参数

全部的 nginx 变量还是非常多的,简单列举几个可能会使用到的:

$args                    #请求中的参数值
$uri                     #请求中的当前URI
$host                    #优先级:HTTP请求行的主机名>"HOST"请求头字段>符合请求的服务器名.请求中的主机头字段,如果请求中的主机头不可用,则为服务器处理请求的服务器名称
$hostname                #主机名
$request_method          #HTTP请求方法,通常为"GET"或"POST"
$server_name             #服务器名
$1                       #location 正则匹配的第一个参数,以此类推可以有 $2...
复制代码

history 多项目配置

Usually we have many projects that use the history route. If the same domain name is maintained but different projects need to be distinguished according to the directory, the previous configuration method cannot be implemented automatically, and the file directory needs to be manually specified, which is obviously not the case. For the result we want, we can modify the matching rules with the help of the parameter variables listed above, and match the corresponding static resource path according to the access path.

location ~ ^(/[^/]+) {  
    root   html/dist/;
    try_files $uri $uri/ $1/;
    index index.html;
}  
复制代码

image.png

image.png

To complete the above demonstration, you need to modify the path of the demo project of vue to the corresponding directory path to complete.

Reference documentation

Nginx configuration details

Careers

The Experience Technology R&D Center is mainly responsible for providing technical support for all end-side products of Xingyun Group with experience technology, providing users with the ultimate experience and making digitalization within reach. The technical architecture includes construction, engineering, micro front-end, UI specification, R&D efficiency, CI/CD, AI intelligence and other technical systems. The experience technology research and development center is composed of front-end team, client team, and Xingyun ecological business team. The team size is 60+. The members are from Internet companies such as Ali, Tencent, Baidu, Tuya, etc., including many technical experts, with strong strength.

All the above products are completed by the full-stack participation of the students in the experience technology team, whether it is front-end & client, or operation and maintenance, database, or AI technology.

If you want to have a further pursuit of technology, have many ideas for engineering but have no opportunities and scenarios, and want to experience a valuable product from 0-1 and then from 1-10 , then there are a lot of fun, interesting, Meaningful technology products are waiting for you .

Guess you like

Origin juejin.im/post/7083177634338701349