Nginx学习

Nginx是什么

Nginx 是一个高性能的 Web 服务器和反向代理服务器
最常见的作用有这几个:

  • 静态资源服务器:直接返回 html/js/css/img
  • 反向代理:把请求转发给后端服务(Node/Java/Python)
  • 负载均衡:把流量分发到多台后端
  • 网关能力:HTTPS 终止、重定向、缓存、压缩(gzip/brotli)、跨域头等

通过Docker学习Nginx

启动Nginx镜像

Nginx的配置文件

通过 nginx 镜像来了解 nginx 的配置文件都有哪些

在 nginx 中,其中比较重要的有以下几个文件,而它们都是有层层关联的:

/etc/nginx/nginx.conf
/etc/nginx/conf.d/default.conf

/etc/nginx/nginx.conf
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
31
user  nginx;
worker_processes auto;

error_log /var/log/nginx/error.log notice;
pid /run/nginx.pid;


events {
worker_connections 1024;
}


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

sendfile on;
#tcp_nopush on;

keepalive_timeout 65;

#gzip on;

include /etc/nginx/conf.d/*.conf;
}
/etc/nginx/conf.d/default.conf
1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

Nginx镜像

nginx


root和index


location

location 用以匹配路由,配置语法如下

location [ = | ~ | * | ^ ] uri { … }

其中 uri 前可提供以下修饰符

  • = 精确匹配,优先级最高。
  • ^~ 前缀匹配,优先级其次。如果同样是前缀匹配,走最长路径。
  • ~ 正则匹配,优先级再次 (~* 只是不区分大小写,不单列)。如果同样是正则匹配,走第一个路径。
  • / 通用匹配,优先级再次。

location修饰符

location优先级


proxy_pass

proxy_pass 反向代理,也是 nginx 最重要的内容,这也是常用的解决跨域的问题。

当使用 proxy_pass 代理路径时,有两种情况

  • 代理服务器地址不含 URI,则此时客户端请求路径与代理服务器路径相同。强烈建议这种方式
  • 代理服务器地址含 URI,则此时客户端请求路径匹配 location,并将其 location 后的路径附在代理服务器地址后。

add_header

Cache

CORS

HSTS

HTTPS,SSL相关

CSP