问题
nginx部署前端项目,
访问网站首页没问题,即网站根目录“https://xxxxxx.com”,
直接访问其他目录时“https://xxxxxx.com/example”,报404(就是nginx找不到相应的 example.html 文件)。
原因
因为 example.html 这个文件全名是带有后缀".html"的,而“/example”只会让nginx去直接寻找文件名是example(没有后缀)的文件,当然是找不到的。
解决方法
解决方法,个人觉得有两种,推荐第二种:
(1)直接url访问全名,比如 “localhost:8080/example.html”,这样就能找到对应子文件;
(2)在nginx.conf配置文件中,加入以下代码(try_files)(见下方解决方案)
更改nginx配置文件。
location / {
root html;
index index.html index.htm;
}
替换为:
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
再次访问。问题解决。
补充:try_files说明(重点)
例子:根据上面的配置,当请求 http://localhost:3004/api 时,$uri
为 /api。当前try_file 具体为:/api
、/api/
、/index.html
,其中 /
表示根目录(根据 root 或 alias 来指定)
- 首先:
检查data
目录中是否存在api
文件,
如果存在,则返回文件;
如果不存在,则进行下一步。 - 其次:
检查data
目录中是否存在api/
目录,
如果存在,则在检查api/
目录中是否存在index.html
或者index.htm
文件(由index
指定);
如果存在,则返回该文件;
如果不存在,则进行下一步。 - 最后:
检查data
目录中是否存在 index.html 文件。
如果存在,则返回文件;
如果不存在,则返回 404。
注意
如果你的网址是https格式的,
那么需要加到监听443端口的location /里。
如果不是,加到80端口。
参考自:
nginx部署,可以访问首页,但是不能直接访问其他路径_nginx反向代理只能访问首页_不会秃头的博客-CSDN博客