本文内系统环境为 Centos 7
本文内配置实例访问域名为:http://nginx.bb.local

特点

占用内存少,性能高,支持并发高

能够实现

反向代理
负载均衡
动静分离
高可用

安装

添加 yum 源

1
rpm -ivh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm

安装 nginx

1
yum -y install nginx

设置 nginx 服务开机启动

1
systemctl enable nginx

常用命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 检测配置文件是否有格式错误
nginx -t

# 查看 nginx 服务当前状态
systemctl status nginx

# 停止 nginx 服务
systemctl stop nginx

# 启动 nginx 服务
systemctl start nginx

# 重启 nginx 服务
systemctl restart nginx

配置语法

  1. 每条指令都是以;结尾,指令与参数之间以空格符号分割
  2. 指令块以{}大括号将多条指令组织在一起
  3. include 语句允许组合多个配置文件以提高可维护性
  4. 使用#号添加注释,提高了可读性
  5. 使用$符号获取变量
  6. 部分指令的参数支持正则表达式

负载均衡

当业务访问量上升,服务器无法应对时,提高硬件性能只能解一时之忧,当前最有效的方式是部署多台服务器共同分担访问压力,这就是负载均衡。

负载均衡配置实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
upstream demo {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
}

server {
listen 80;
server_name nginx.bb.local;

location / {
proxy_pass http://demo;
}
}

反向代理

  1. 正向代理
    我们通常提到的梯子,就是正向代理服务器,通过一台可以访问指定网络的服务器进行资源访问。此时客户端是知道有代理这一操作的。

  2. 反向代理
    反向代理,其实客户端对代理是无感知的,因为客户端不需要任何配置就可以访问,我们只需要将请求发送到反向代理服务器,由反向代理服务器去选择目标服务器获取数据后,在返回给客户端,此时反向代理服务器和目标服务器对外就是一个服务器,暴露的是代理服务器地址,隐藏了真实服务器 IP 地址。

反向代理配置实例:

1
2
3
location /oss {
proxy_pass http://game-brew.oss-cn-hangzhou.aliyuncs.com/;
}

上面的例子在访问 http://nginx.bb.local/oss/ 路径下的资源会转发到 http://game-brew.oss-cn-hangzhou.aliyuncs.com/
如下:
http://nginx.bb.local/oss/head.jpg
http://game-brew.oss-cn-hangzhou.aliyuncs.com/head.jpg
两个 url 都能访问到 head.jpg 这张图片,可以解决在 Canvas 中使用的图片资源的跨域问题

动静分离

静态资源交由 nginx 直接提供访问,减少动态内容服务器处理压力。

静态资源服务器配置实例:

1
2
3
4
location ~^/(images|stylesheets|download|javascript) {
root /usr/file;
autoindex on;
}

上面代码实现了当访问路径为 images、stylesheets、download、javascript 开头时,会直接匹配_usr_file 文件夹下的文件返回。

设置 CORS

解决跨域除了做反向代理,还可以通过配置 CORS ,允许前端在满足某些条件的情况下跨域。

1
2
3
4
5
6
7
add_header 'Access-Control-Allow-Origin' 'http://demo.bb.local';
add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Content-Type, token';

if ($request_method = 'OPTIONS') {
return 200;
}

开启 gzip

1
2
3
4
5
gzip on; # 打开
gzip_min_length 1; # 小于 1 字节,就不在压缩了
gzip_comp_level 2; # 压缩级别
gzip_types text/plain application/x-javascript text/css application/xml application/javascript text/javascript applic
ation/x-httpd-php image/jpeg image/gif image/png;

高可用

此为高级功能,我还没学到。