nginx 指令
location
location指令用于配置请求的匹配规则,并指定对应的处理方式。nginx 按照以下顺序匹配location块:
- 精准匹配,如果请求的uri 和location中的路径完全匹配,nginx采用该块处理,如 location = /path/to/resource {};
- 前缀匹配,如果请求的uri 以location中的路径开头,则停止继续匹配其它location,采用此处的location块,如
location ^~ /path/to; - 正则配置,如果请求的uri匹配location块中的正则,采用此处的location块,
~*不区分大小写, 如location ~ /path/to或location ~ * /path/to; - 普通前缀匹配,如果请求的uri以location的路径开头,则将其暂存,继续寻找其它location块,最后采用location路径最长的那个location块,如
location /path/to。
location 块 root 用于指定资源的根路径,如 root build 请求url是/path/to则nginx到build/path/to查找资源。
location 块 alias 用别名替换请求路径,如 location /images/ { alias /build} 请求url是/images/a.png则nginx到/build/a.png查找资源。
location 块 try_files 用于找不到资源时的备选项,try_files path1 [path2...] fallback其中,path1, path2, ... 是要尝试的文件路径或 URI。当请求无法直接匹配到这些文件时,Nginx 将按照指定的顺序尝试这些备选项。如果找到匹配的文件,则将其返回给客户端。fallback 是一个备选项,表示当所有的备选路径都无法匹配时,将请求转发到指定的 URI 或处理逻辑。
location 块 index 指令用于指定当请求为路径时,默认打开的文件。
nginx 二级目录配置单页应用
在根目录下创建test文件夹用于存放子单页应用。文件结构如下:
- build
- index.html
- assets
- test
- index.html
- assets
nginx 配置如下:
location /test/ {
root /opt/build;
try_files $uri $uri/ /test/index.html?$args;
index index.html index.htm;
}
访问url:http://172.20.7.92:3600/test/login
寻找策略:
- /opt/build/test/login 未找到 login 文件
- /opt/build/test/login/index.html 未找到 index.html 文件
- 重定向到 /test/index.html?$args
- /opt/build/test/index.html 找到index.html文件
nginx 启停
- reload: sudo service nginx reload
- windows reload
.\nginx -s reload - windows 停止
.\nginx -s stop - windows 启动
.\nginx
其它
- 更新配置重启后,chrome可能有缓存,无痕模式打开网页;
- windows 环境下使用 nginx 命令,要加相对路径,如
.\nginx