10 分钟学会 Nginx 部署应用(React, Vue, Angular, 静态文件,反向代理,HTTPS,Docker)

# 10 分钟学会 Nginx 部署应用(React, Vue, Angular, 静态文件,反向代理,HTTPS,Docker)

# 了解 Nginx

  • 名称:Nginx
  • 读音:Engine X
  • 作用:网络服务器,也可用作反向代理,负载均衡,邮箱代理,Http缓存
  • 优点:高性能,配置简单,适合处理静态文件
  • 支持平台:Linux 最常用,Windows,MacOS,BSD 也支持

# Nginx 安装

遍地都是教程。

菜鸟教程 (opens new window)

官方文档-英语 (opens new window)

cnblog (opens new window)

# 配置文件的格式

专用配置格式,非专业就大概了解一下。后面说具体部署方式。

  • 注视以 # 开始
  • {} 区分配置块
  • 每一条配置行后需要跟随 ; 号,
# 全局配置
worker_processes  1;
xxx on;

# events 块,配置网络连接相关
events {

}

# http 块,主要配置块,包裹代理配置,缓存,日志等,可配置多个服务入口(server)
http {

  # 负载均衡用的多服务器配置,myapp 是示例的服务名字
  upstream myapp {

  }

  # 一个 server 块即一个虚拟主机服务,可以有多个
  server {
    
    # location 块,配置路由,自定义请求转发的关键,下面 `location` 之后到 `{` 之前的字符串是匹配规则。
    location ~ *^.+$ {

    }
  }

  server {

  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

上面展示了一下配置。下面根据这个规则来展示一下怎么使用 Nginx 部署应用

# 部署静态网页和单页面网页(如 React,Vue,Angular等框架构建出来的应用)应用

我们跟据默认配置进行修改。

先举个普通静态网站的例子:

  • 我们要部署的网站的域名叫 showmecode.cc
  • 静态文件夹所在的路径为 /www/examples/showmecode_cc/
  • 日志文件地址:/www/wwwlogs/showmecode_cc.log
  • 静态服务资源的请求(Url 以 /imgs 开头)应该指向:/www/assets/ 文件夹
  • 禁止客户端访问服务端专用私密文件

核心配置就可以像下面这么写

# 在 http 块中添加虚拟主机配置,其他配置一般按照默认的来,下面只关注核心配置。
http {
  server {
    # 服务运行在 80 端口
    listen 80; 

    # 该服务只能通过 下面配置的域名或ip 访问
    server_name showmecode.cc www.showmecode.cc 192.168.1.1;

    # 网站文件根目录
    root /www/examples/showmecode_cc;

    # nginx 要去找的默认文件
    index index.php index.html index.htm default.php default.htm default.html;

    # 重定向 /imgs 路径的请求如 /imgs/xxx 等请求到指定地方
    location /imgs {
      root /www/assets;
      index index.html;
    }

    # 日志文件路径
    access_log /www/wwwlogs/showmecode_cc.log;
    error_log /www/wwwlogs/showmecode_cc.error.log;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

静态网站和这里逻辑很相似

    # 在上述的 server 块中(如 L15 index 配置的下一行)加配置.
    # 此配置会将所有请求转发到 index.html
    try_files $uri $uri/ /index.html;
    # 注意配置的转发规则先匹配先处理的方案,所以上一句配置加在 16 行后,/imgs 的路由无效了
1
2
3
4

# 配置使支持 HTTPS,HTTP2,IPV6地址

# 配置反向代理

# 配置负载均衡

# WebSocket 配置

# 巧用 include 语句,拆分配置文件

# 假设你在用 docker 部署

# 鸣谢参考

  1. 菜鸟教程-安装Nginx (opens new window)
  2. 官方文档-安装Nginx-英语 (opens new window)
  3. cnblog-安装Nginx (opens new window)
  4. Nginx 配置教程 (opens new window)
  5. nginx部署React项目 (opens new window)
  6. Nginx配置转发WebSocket功能 (opens new window)
  7. 从零学nginx-windows下reload配置无效及如何重启 (opens new window)
  8. Nginx 服务器 SSL 证书安装部署 (opens new window)
  9. Docker容器部署 Nginx服务 (opens new window)
  10. Using nginx as HTTP load balancer (opens new window)