目录
目录结构
服务器安装好后的Nginx一般会放在usr/local/nginx目录下面,进入Nginx的主目录我们可以看到这些文件夹
client_body_temp conf fastcgi_temp html logs proxy_temp sbin scgi_temp uwsgi_temp
client_body_temp, fastcgi_temp, proxy_temp ,scgi_temp在刚安装后是没有的,主要用来存放运行过程中的临时文件
conf
用来存放配置文件相关
html
用来存放静态文件的默认目录 html、css等
sbin
nginx的主程序
Nginx配置
nginx的配置文件在conf目录下面的nginx.conf文件中,可以通过配置实现反向代理,负载均衡等应用,
编辑打开
vi /usr/local/nginx/conf/nginx.conf
去掉注释的,最基本的就一些
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
worker_processes 默认为1,表示开启一个业务进程
worker_connections 单个业务进程可接受连接数
虚拟主机配置
静态HTTP服务器
服务器可以对客户端可以通过发送相匹配的路径请求,做出拦截,将对应的静态文件(如HTML、图片)通过HTTP协议展现给客户端。
server {
listen 80; # 端口号
location / {
root /usr/local/nginx/html; # 静态文件路径
}
}
反向代理服务器
目前的前后端项目,都需要使用路径重写,来解决跨域问题,但路径重写在项目打包部署时会失效(个人经历与理解),此时部署就可以使用代理来实现路径的重写
server {
listen 8093; # 监听端口号
server_name www.liyingjie2001.cn; #监听域名,由于一个服务器可以绑定多个域名
location / { # 路径匹配
root weavingDict; #项目根路径
index index.html index.htm;
}
location /prod-api/ { #匹配路径
proxy_pass http://liyingjie2001.cn:800/; #代理到相应地址
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
说明:在服务器上有一个后端服务,端口为800
前端项目端口为8093,当我们访问前端项目,需要调用后端的接口数据时,需要调用端口800的服务,配置了代理之后,我们访问https://www.liyingjie2001.cn:8093/prod-api/getCache时,就会被代理到https://www.liyingjie2001.cn:800/getCache后端的项目
负载均衡
基于反向代理实现,
upstream httpds {#演示负载均衡
server 192.168.31.117:8001;
server 192.168.31.117:8002;
}
server { #演示负载均衡
listen 86;
server_name localhost;
location / {
proxy_pass http://httpds; #httpds为集群名
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
location匹配顺序
- 多个正则location直接按书写顺序匹配,成功后就不会继续往后面匹配
- 普通(非正则)location会一直往下,直到找到匹配度最高的(最大前缀匹配)
- 当普通location与正则location同时存在,如果正则匹配成功,则不会再执行普通匹配
- 所有类型location存在时,“=”匹配 > “^~”匹配 > 正则匹配 > 普通(最大前缀匹配)