nginx 配置多页面

1,028 阅读1分钟

需求分析

项目使用 vue 进行开发,vue 项目中实现了多页面:有一个 index.html 文件和一个 fill-in.html文件

需求如下:

访问: example.com:8081/
响应:/usr/8081/index.html

访问:example.com:8081/fill-in
访问:example.com:8081/fill-in/
响应:/usr/8081/index.html (index.html 会展示 404 页面)

访问:example.com:8081/fill-in/412 (后面的 412 代指任意数字)
响应:/usr/8081/fill-in.html

解决方案

    server {
        listen          8081;
        location / {
                root /usr/8081;
                try_files $uri $uri/ /index.html;
        }
        location = /fill-in/ {
                root /usr/8081;
                try_files /index.html /index.html;
        }
        location /fill-in/ {
                root /usr/8081;
                try_files $uri $uri/ /fill-in.html;
        }
    } 

解释

location 就是用于指定请求路由的,可以配置:访问 /a 时给他什么内容,访问 /b 时给他什么内容

try_files 可以用在 location 中,用于声明,要给这个请求的资源路径。
在这里有一个变量 $uri,他代表的意思是用户请求的路径。比如
用户访问 example.com/index.html 时,$uri 就代表 index.html;
用户访问 example.com/index.html/ 时, $uri 就代表 index.html/;
用户访问 example.com/a/b/ 时, $uri 就代表 a/b/;


先看 location = /fill-in/,其中的 = 代表代表精准匹配字符串,所以他只匹配 example.com:8081/fill-in/ 这一种情况。

再看 location /fill-in/,匹配的是 example.com:8081/fill-in/412 这种情况。

其他的资源,就都属于 location / 了。

注意 location / 中的 try_files $uri $uri/ /index.html; 不要错写成 try_files /index.html /index.html;。如果错写了,则会出现请求任意资源(js、css)都返回 index.html 的情况。
这个时候,控制台会出现 Uncaught SyntaxError: Unexpected token '<' (at fill-in.46755ccb.js:1:1) 报错。

注意 try_files 至少要有两个参数,所以当你想要将任意请求都返回 index.html 文件时,别忘记在后面补上一个参数。不要错写成 try_files /index.html;。不过其实写错了也没事,nginx -t 会提示你 nginx: [emerg] invalid number of arguments in "try_files" directive

参考资料

try_files 参考资料

location 参考资料