nginx中部署vue项目

前言

nginx是一个高性能的HTTP和反向代理web服务器。作为Web服务器,nginx处理静态文件、索引文件以及自动索引效率非常高。

启动nginx服务

start nginx

浏览器中输入: localhost:80
在这里插入图片描述
说明服务起来了。

部署Vue项目

下面的示例,前端Vue项目使用Vue CLI3创建

1 部署到根目录

1)vue配置

  • 路由模式: history。(hash模式也可以)
  • publicPath ‘./’

完了npm run build进行打包。

2)nginx配置及部署

  • 修改nginx.conf

    location / {
        root    app; #项目文件位置
        index  index.html;
        try_files $uri $uri/ /index.html;
    }
    

    在这里插入图片描述

    完了重启nginx服务

    nginx -s reload
    

3)路由模式及地址匹配

vue项目中有两个页面,主页和about页面。

history模式

  • / 匹配 localhost:8010

  • /about 匹配 localhost:8010/about

hash模式

  • / -> http://localhost:8010/#/
  • /about -> http://localhost:8010/#/about

2 部署到子目录

也就是通过 localhost:8010/子目录/xx 访问项目。
这个也是要在Vue和Nginx中分别配置。

子目录名以 gis 为例:

1) vue配置

  • 路由base属性:
const router = new VueRouter({
    
    
  routes,
  mode: 'history',
  base: '/gis/'
})
  • vue.config.js
module.exports = {
    
    
	publicPath: '/gis/',
	.....
}

配置完后,重新打包。

这个在Vue CLI文档中也有说明。
在这里插入图片描述

2)nginx配置

可以在nginx中新建目录gis,将上面配置后的打包结果(dist目录内的内容)复制进去。你也可以放到任意目录,看个人习惯。

 location / {
    
    
     root    app; #项目文件位置
     index  index.html;
     try_files $uri $uri/ /index.html;
 }
 # 子目录
 location ^~/gis {
    
    
     alias  gis; #项目文件位置
     index  index.html;
     try_files $uri $uri/ /gis/index.html;
 }

完成后,重启nginx服务

nginx -s reload

参考:
1.nginx百度百科
2.Vue CLI配置参考
3.Vue Router后端配置例子

猜你喜欢

转载自blog.csdn.net/u012413551/article/details/119392398