参考资料
安装
mac
# 安装
brew install nginx
# 卸载
brew uninstall nginx
常用指令
# 启动
nginx
# 重启
nginx -s reload
# 停止
nginx -s stop
# 查看nginx配置信息
cat /usr/local/etc/nginx/nginx.conf
# 查看是否配置正确
nginx -t
基础知识入门
1 内置变量说明
2 location语法规则
# location语法
locaition 各种符号 匹配的uri或者uri正则表达式 {
}
各种符号
- 空格
- = 精准匹配uri,不支持正则语法
- ~ 正则表达式区分大小写匹配uri
- ~* 正则表达式区分大小写匹配uri
- ^~ 匹配uri,不支持正则语法
- 优先级:
=
>^~
>~/~*
>空格
匹配的uri或者uri正则表达式
- / 匹配 /a /ab /abcd /acd
- /a 匹配 /a /abc /abcd/a 等以/a开头
- /.*/abc 匹配 /c/abc /c/c/abc /c/c/abc/c
- /$ 匹配 a/ b/ c/ 等以/结尾的uri
3 index、rewrite、try_files
- index 设置默认的索引文件,常用index.html
- rewrite 重定向请求路径
- try_files 依次尝试查找文件
业务场景
配置csr多页面静态网站
假设我的项目是一个多页面入口,打包完成后目录结构如下:
h5是一个页面入口,downloads是另外一个页面入口,其中h5是具有history路由的页面,配置如下
修改配置文件
vim /usr/local/etc/nginx/nginx.conf
修改nginx.conf文件
# user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
# 定义监听的端口号
listen 8080;
# 定义域名为 localhost
server_name localhost;
# 定义访问的根目录,也就是当浏览器输入 http://localhost:8080/ 时, 访问的是/Applications/gitWork/www.pook.com/dist此目录
root /Applications/gitWork/www.pook.com/dist;
index index.html;
# 如果uri 等于 / 则找到 定义的根目录/index.html
location = / {
index /pages/h5/index.html;
}
location / {
try_files $uri $uri/ /pages/h5/index.html;
}
}
include servers/*;
}
配置next.js ssg项目
# user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
# 定义监听的端口号
listen 8080;
# 定义域名为 localhost
server_name localhost;
# 定义访问的根目录,也就是当浏览器输入 http://localhost:8080/ 时, 访问的是/Applications/gitWork/template/nextJs/react/out此目录
root /Applications/gitWork/template/nextJs/react/out;
index index.html;
# 如果uri 等于 / 则找到 定义的根目录/index.html
location = / {
index index.html;
}
# 如果uri 以 / 结尾, 则重定向请求uri,匹配到 / 前面的字符串, 通过$1获取后,拼接 .html 举例 localhost:8080/dashboard/ ==> 定义的根目录/dashboard.html
location ~ /$ {
rewrite ^(.*)/$ $1.html break;
}
# 如果是其uri ,则尝试查找以下三个顺序。
location / {
try_files $uri $uri/ $uri.html;
}
}
include servers/*;
}
配置反向代理接口
- nginx的域名为 localhost:8080
- 接口的域名为 192.168.23:9001
通过访问
www.a.com/proxy/url
来请求到192.168.23:9001/url
并返回,这一过程,用户实际上是不知道请求的是192.168.23:9001/url
。
# user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
# 定义监听的端口号
listen 8080;
# 定义域名为 localhost
server_name localhost;
# 设置接口代理哦
location /proxy/ {
proxy_pass http://localhost:9001/;
}
}
include servers/*;
}
debug
# 实时展示错误日志,方便我们查看nginx访问的情况
tail -f /usr/local/var/log/nginx/*.log