Nginx如何正确配置部署在子目录的vue项目

网站的目录结构如下:

www/
├─ index.html
├─blog/
│ ├─dist/
│ ├─index.html

blog下是打包好的vue+vue-router项目。

此时nginx配置如下

    server {
         listen 443;
         server_name localhost;
         ssl on;
         root /var/ftp/www/;
         index index.html;
         #ssl配置省略
         location /api/ {
            proxy_pass https://localhost:3010;
         }
    } 

直接访问https://域名/blog/,是没问题的,可是当刷新的时候,blog的子页面就会404,查阅后发现是因为vue-router开启了history模式,于是按照官方文档的方法在server里添加了

try_files $uri $uri/ /index.html;

这样虽然不会404,但是页面全部转到了根目录的index.html,于是调整了nginx的配置如下:

    server {
         listen 443;
         server_name localhost;
         ssl on;
         root /var/ftp/www/;
         index index.html;
         #ssl配置省略
         location /blog/ {
            root /var/ftp/www/blog/;
            index index.html;
         }
         location /api/ {
            proxy_pass https://localhost:3010;
         }
    } 

这时候访问https://域名/blog/ 直接就报了404错误,然后试着修改nginx配置如下:

    server {
         listen 443;
         server_name localhost;
         ssl on;
         #ssl配置省略
         location /blog/ {
            root /var/ftp/www/blog/;
            index index.html;
         }
         location /api/ {
            proxy_pass https://localhost:3010;
         }
         location / {
            root /var/ftp/www/;
            index index.html;
         }
    } 

仍然会报404错误,请问是哪里搞错了,折腾了一晚上头发都快掉光了Q A Q

阅读 28.8k
2 个回答

哈哈...头发掉光了再回答你!

location /api/ {
            proxy_pass https://localhost:3010;
         }

注意location后面写成/api//api是不一样的(特别注意哦),你的node启动了服务,例如是8080的端口, nginx代理直接代理过去就好了,如果你想把/blog代理不需要加后面的斜杠哦,而且域名访问的时候应该是https://www.xxx.com/blog即可,另外root的路径指向,应该从根目录开始哦

感谢楼上大大的回答~问题已经解决了~虽然不知道解决的方法是否正确,还是记录一下,如果方法有错误的地方还请私信或者评论我指出 感谢!
今天在修改设置的时候突然想起来nginx是有错误日志的,于是赶忙下载了下来,然后发现了问题

[error] 27661#0: *1 open() "/var/ftp/www/blog/blog" failed (2: No such file or directory)

很显然nginx认为我对于/blog设置的根目录是/var/ftp/www/blog/,而我访问http://域名/blog时,自动又加了一个/blog,导致了404错误,于是我把location /blog的root改成了/var/ftp/www/,此时访问正常,然而刷新还是会回到根目录的index.html,于是将location /blog下面的try_files改成了

try_files $uri $uri/ /blog/index.html;

这下就一切正常了,虽然问题时解决了,但是总感觉哪里怪怪的,感觉和网上前辈们写的一些资料出入很大。。看来之后还是要多查一下资料搞清楚这个问题啊OTZ

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题