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;
}
}
}
全局块 | location |
---|---|
最常见的配置是本虚拟机主机的监听配置和本虚拟主机的名称或IP配置 | 这块的主要作用是基于 Nginx 服务器接收到的请求字符串、对虚拟主机名称(也可以是IP别名)之外的字符串(例如 /uri-string)进行匹配,对特定的请求进行处理。地址定向、数据缓存和应答控制等功能,还有许多第三方模块的配置也在这里进行。 |
字段 | 功能 |
---|---|
worker_processes | 指明nginx要开启的进程数 |
worker_connections | 单个工作进程可以允许同时建立外部连接的数量 |
defult_type | 响应类型:有application/octet-stream(下载)和application/text/html(网页 ) |
include | 配置多的时候会分成多个文件,可以用此指令汇总 |
sendfile | 提高文件的传输速率,开启后会用sendFile() |
keepalive_timeout | 规定http请求keep-alive持续的时间,不要太大,好释放资源,提高性能 |
location | 通过指定模式来与客户端请求的URI相匹配 |
server_name | 指明host |
listen | 该字段出现在server里,指明端口号 |
error_page | 当发生错误的时候能够显示一个预定义的uri |
proxy_pass | 反向代理字段 |
upstream | 负载均衡配置模块 |
location = /a{
echo "this is the most higt level"
}
location ^~ /a {
echo "this is the second level"
}
location ~ /\w {
echo "this is the third level"
}
location / {
echo "this is the final level"
}
作为一个前端er,了解这些就够了吧,接下来就进入主菜
开启nginx后默认是80端口,我因为端口号被占用,修改成了8080,访问localhost:8080
我用node自己开了个服务,端口号为8080,访问成功:
反向代理我们只需要用到proxy_pass字段,像这样:
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;
# 响应类型改为html
default_type text/html;
location / {
proxy_pass http://localhost:8080
}
}
}
可以看到访问默认的80端口,也会因反向代理转到8080端口
反向代理需要注意的点就是proxy_pass的路径要与location的规则一起用
负载均衡的职责是将网络请求,或者其他形式的负载「均摊」到不同的机器上。避免集群中部分服务器压力过大,而另一些服务器比较空闲的情况。
通过负载均衡,可以让每台服务器获取到适合自己处理能力的负载。在为高负载服务器分流的同时,还可以避免资源浪费,一举两得。
负载均衡可分为软件负载均衡和硬件负载均衡。在我们日常开发中,一般很难接触到硬件负载均衡。但软件负载均衡还是比如我们接下来会讲到的ngxin
可以这么配置
worker_processes 1;
events {
worker_connections 1024;
}
####################################
####### 在这里添加一个upstream 字段####
upstream serverGroups{
server localhost:80;
server localhost:8080;
server localhost:8081;
}
####################################
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
default_type text/html;
location / {
####################################
# 在这里啊host替换成上面的upstream名字 #
proxy_pass http://serverGroups
}
}
}
看看效果
自此,反向代理和负载均衡就大概是这样,我觉得作为前端er了解知道怎么弄就行,不需要去深入了解配置参数啥的