Nginx介绍

之前瑞吉外卖的时候就使用过nginx ,当时blog还没搭出来所以没记笔记,我觉得这个可以单独拿出来讲讲,所以就多开了一篇。

Nginx的三大特性

请求转发

一般来说客户端或者说浏览器发送请求,不在直接的发送给后台服务器,而是使用nginx接收,然后再通过nginx发送给后端服务器做响应。
假设后台服务器有很多台,那么nginx可以根据请求转发的url路径匹配原则转发到具体的某个服务器中,有点中间商的味道。
我自己觉得好处就是隐藏了后台服务器,无法知晓后台服务器的端口号,客户端无法直接访问后台,减少被攻击的可能性。

负载均衡

假设有两台服务器都是同一个项目部署的(集群)。负载均衡指的就是客户端发送请求给nginx端口为9001,然后nginx会把客户端的请求平均分摊到两台服务器中,一般来说默认采用的是轮询的方式平均(你一次我一次),但是我们也可以实现按权位来分配,比如给第一台大概百分之六十的请求,第二台大概百分之四十。还有很多算法,比如根据谁的请求时间最短就直接发给谁等等。

动静分离

说白了就把静态资源放在了nginx服务器上,比如图片,然后把代码,动态资源放置在tomcat服务器中

Nginx的基本使用

安装

去官网安装window版的nginx,最好是使用Linux的nginx,功能更加全面,后续如果我再遇到Linux版的nginx我会在这里补充。现在谷粒的项目用window就够了,很好操作也好改配置,部署项目的话必须要用Linux版,不过后面用网关来部署就不用nginx了,所以window足够了。

常用指令

window开始指令就是在.exe所在文件夹输入cmd直接输入文件名称nginx.exe就可以开启
提醒!直接关闭命令窗口无法关闭nginx服务,可以输入nginx -s stop命令停止
修改完配置文件后可以直接使用重启命令 nginx -s reload

修改配置文件

不管是window还是Linux中修改配置文件的地方永远是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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
server {
#改成81端口防止80被占用出问题
listen 81;
server_name localhost;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root html;
index index.html index.htm;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}




# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;

# location / {
# root html;
# index index.html index.htm;
# }
#}
#这个就是根据我们后台的服务器地址修改,有几个服务器就配置几个
server {
listen 9001;
server_name localhost;

location ~ /eduservice/ {
proxy_pass http://localhost:8001;
}

location ~ /eduoss/ {
proxy_pass http://localhost:8002;
}
}

最后

要记录一下吧,今天是我的生日啦,写完这篇我就要去许愿啦,真的希望能够实现叭
嘉楠,祝你生日快乐
一切的沉淀终将会有收获