Nginx最小配置文件
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
| # 工作进程的个数 worker_processes 1;
events { # 每个工作进程的连接数 worker_connections 1024; }
http { # include是将外部的配置文件引入到此配置中 # mime.types中定义了服务器端返回的二进制流所对应的文件类型 include mime.types; # 默认的类型,即mime.types中没有包含的,那么就会使用默认类型 default_type application/octet-stream; # 数据零拷贝,不开启数据就需要从磁盘读到应用的内存,再从内存发到网络接口 # 开启后Nginx直接向操作系统发送一个信号,数据就直接发送至网络接口,省去了一步IO操作 sendfile on; keepalive_timeout 65; # 虚拟主机 server { # 监听的端口 listen 80; # 域名/主机名 server_name localhost;
# uri(统一资源定位) location / { # 对应的主目录 root html; # 默认页 index index.html index.htm; } # 服务器错误页 error_page 500 502 503 504 /50x.html; # 错误页所在目录 location = /50x.html { root html; } } }
|
一个目录对应多个域名
1 2 3 4 5 6 7 8 9 10 11 12
| ...... server { listen 80; # 多个域名用空格隔开,这样不管是访问那个域名,都会定位到下方 server_name test1.com test2.com;
location / { root html; index index.html index.htm; } ...... }
|
域名通配符匹配
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
| # 全匹配 server { listen 80; # 访问www.test.com可以定位到abc目录 server_name www.test.com;
location / { root abc; index index.html index.htm; } ...... } # 通配符前匹配 server { listen 80; # 访问a.test.com或者b.test.com等除了www.test.com,都会定位到html目录 server_name *.test.com;
location / { root html; index index.html index.htm; } ...... } # 通配符后匹配 server { listen 80; # 访问a.test.cn/a.test.top等都会匹配到www目录(除了www.test.com、a.test.com) server_name a.test.*;
location / { root www; index index.html index.htm; } ...... }
|
注意:多个server配置是有先后顺序的,上面的例子也说明了这一点
反向代理
1 2 3 4 5 6 7 8 9 10 11
| ...... server { listen 80; server_name localhost;
location / { # 反向代理,访问http://localhost就会代理到https://www.baidu.com proxy_pass https://www.baidu.com; } ...... }
|
负载均衡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| ...... //需要负载均衡的服务器,weight表示权重 upstream myalias { server 192.168.0.100:80 weight=8; server 192.168.0.101:80 weight=2; } server { listen 80; server_name localhost;
location / { //反向代理,加上负载均衡的别名 proxy_pass https://myalias; } ...... }
|