一. 配置说明1
以Win下nginx 1.19.6 为例,默认的配置文件如下(删除注释后)
下面配置中的events、http、server、location、upstream等属于配置项块。而worker_processes 、worker_connections、include、listen 属于配置项块中的属性。 /50x.html 属于配置块的特定参数参数。其中server块嵌套于http块,其可以直接继承访问Http块当中的参数。
注:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
http模块下Server下的含义:
A. listen:表示当前的代理服务器监听的端口,默认的是监听80端口。
B. server_name:表示主机名称,后面可以跟多个主机名称,比如:
C. location:表示匹配的路径,这时配置了/表示所有请求都被匹配到这里
A. root:里面配置了root时表示当匹配这个请求的路径时,将会在这个文件夹内寻找相应的文件,主要用于静态文件。
B. index:当没有指定主页时,默认会选择这个指定的文件,它可以有多个,并按顺序来加载,如果第一个不存在,则找第二个,依此类推。
C. proxy_pass:代理地址
注意:可以配置多个server,同时监听多个端口的。
1. 基本配置
(1). location详解
语法:location[=|~|~*|^~|@]/uri/{……} 配置块:server
-
=表示把URI作为字符串,以便与参数中的uri做完全匹配。
-
/ 基于uri目录匹配
-
~表示正则匹配URI时是字母大小写敏感的。
-
~*表示正则匹配URI时忽略字母大小写问题。
-
^~表示正则匹配URI时只需要其前半部分与uri参数匹配即可。
匹配优先规则:
-
精确匹配优先 =
-
正则匹配优先 ^~
-
前缀最大匹配优先。
-
配置靠前优化
(2). root 和alias区别
A. root
可配置在 server与location中,基于ROOT路径+URL中路径去寻找指定文件。
B. alias
只能配置location 中。基于alias 路径+ URL移除location 前缀后的路径来寻找文件。
location /V1 { alias /www/old_site; index index.html index.htm; } #防问规则如下 URL:http://xxx:xx/V1/a.html 最终寻址:/www/old_site/a.thml
2. 动态代理
(1). 正向代理
是指客户端与目标服务器之间增加一个代理服务器,客户端直接访问代理服务器,在由代理服务器访问目标服务器并返回客户端并返回 。这个过程当中客户端需要知道代理服务器地址,并配置连接。 比如FQ,我们不能直接访问外国的某些网站,需要中间找个代理。
(2). 反向代理
是指户端访问目标服务器,在目标服务内部有一个统一接入网关,用来将请求转发至后端真正处理的服务器并返回结果。这个过程当中客户端不需要知道代理服务器地址,代理对客户端而言是透明的。
(3). 二者区别
(4). 代理相关参数
A. 参数如下:
proxy_pass # 代理服务 proxy_redirect off; # 是否允许重定向 proxy_set_header Host $host; # 传 header 参数至后端服务 proxy_set_header X-Forwarded-For $remote_addr; # 设置request header 即客户端IP 地址 proxy_connect_timeout 90; # 连接代理服务超时时间 proxy_send_timeout 90; # 请求发送最大时间 proxy_read_timeout 90; # 读取最大时间 proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k;
B. 基本配置
使用 proxy_pass属性进行代理,如下配置, 访问 http://localhost:8080/ 将会被代理到 http://localhost:9001/ 上;访问 http://localhost:8090/ 将会被代理到 http://localhost:9002/
代码如下:
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 8080; server_name localhost; location / { proxy_pass http://localhost:9001; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server { listen 8090; server_name localhost; location / { proxy_pass http://localhost:9002; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }