常用指令
windows: 进入到nginx 主文件夹路径下面
nginx -s stop 快速停止nginx
nginx -s reload 热重启
start nginx(启动windows)
nginx -c /etc/nginx/nginx.conf 按照特定配置文件 启动Linux
反向代理多端口
可以配置多个监听端口设置不同的规则:如下就可以访问
http://localhost –> index.html
http://localhost:8088 –> http://localhost:8082/recordZs/
通过配置proxy_pass 设置服务器跳转,注意后缀要多待一个/
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; } } server { listen 8088; server_name recordZs; location / { proxy_pass http://localhost:8082/recordZs/; } }
|
反向代理location规则
server { listen 8088; server_name recordZs; location / { proxy_pass http://localhost:8082/recordZs/; } }
|
匹配成功之后,所有的 8088/的请求 都会转到 以http://localhost:8082/recordZs/开头的请求中
例如 localhost:8088/index.jsp http://localhost:8082/recordZs/index.jsp
location匹配命令
- ~ 波浪线表示执行一个正则匹配,区分大小写( -—$ 局部匹配 ^—-$ 打头和末位匹配 )
- ~* 表示执行一个正则匹配,不区分大小写
- ^~ 表示普通字符匹配,如果该选项匹配,只匹配该选项,不匹配别的选项,一般用来匹配目录
- = 进行普通字符精确匹配
- @ 定义一个命名的 location,使用在内部定向时,例如 error_page, try_files
- $ 引用变量($server_name表示引用一串地址)
1.开头和结尾匹配 ^ $ server { listen 80; server_name edu.gehealthcare.cn; #表示请求以 /index打头和结尾的请求 重定向到http://$server_name/edu_index 请求 location ~ ^(/index)$ { return 301 http://$server_name/edu_index; } } 2.精准匹配: localhost/test -->http://127.0.0.1:8082/webTest/login.do location = /test{ proxy_pass http://127.0.0.1:8082/webTest/login.do; } 3.完全匹配: localhost --> http://127.0.0.1:8082/webTest/login.do location / { # 匹配任何请求,因为所有请求都是以"/"开始 # 但是更长字符匹配或者正则表达式匹配会优先匹配 proxy_pass http://127.0.0.1:8082/webTest/login.do; } location ^~ /images/ { # 匹配任何以 /images/ 开始的请求,并停止匹配 其它location [ configuration C ] } location ~* .(gif|jpg|jpeg)$ { # 匹配以 gif, jpg, or jpeg结尾的请求. # 但是所有 /images/ 目录的请求将由 [Configuration C]处理. [ configuration D ] }
|
动静分离匹配
注意事项:
1) windows的话 路径一定是正斜杠” / “, 而不能是 反斜杠 啊
2) 静态资源的话,用 root 开头
3) 静态资源的开头要按照规则 IP:8088/RESIRYSE
server { listen 8088; server_name recordZs; location ~ \.(gif|jpg|jpeg|png|bmp|swf)$ { root C:/Users/502764158/Desktop/test; } # 所有以/dh-edu/resources/images 开头的 请求都会复制到/dh/dh-edu/resources/images 路径下去寻找资源 location ~ ^(/dh-edu/resources/images|/dh-edu/resources/video|/dh-edu/resources/pdf) { root /dh; } location ~ \.(jsp|do)$ { proxy_pass http://localhost:8082; } }
|
静态资源代码 ip为 反向代理的监听端口 8088,而不是tomcat的端口

~ 表示匹配正则表达式 \开始匹配 $表示结束匹配
注意正则表达式匹配的话 proxy_pass中不能包含 URL 元素,也就是 只有 http:*:8080 后面不能有元素
# 所有静态请求都由nginx处理,存放目录为html location ~ \.(gif|jpg|jpeg|png|bmp|swf)$ { root html; } # 所有动态请求都转发给tomcat处理 location ~ \.(jsp|do)$ { proxy_pass http://local_tomcat; } # 匹配所有以recordZs 打头的请求 location ~ ^recordZs*$ { proxy_pass http://localhost:8082; }
|
负载均衡
- proxy_pass http://my_tomcat; 即可
- 可以设置weight,值越大,访问的概率越高
upstream my_tomcat { server 127.0.0.1:8082 weight=2; server 127.0.0.1:8080 weight=1; } server { listen 80; server_name localhost; location / { proxy_pass http://my_tomcat; } }
|