项目环境:
以windows版为例,下载niginx压缩包并解压到任意目录,双击nginx.exe
,在浏览器中访问http://localhost
,若是出现Welcome to nginx!
页面则说明成功。前端
nginx经常使用命令以下:vue
nginx -h # 打开帮助 nginx -t # 检查配置文件是否正确 # 如下命令均要先启动nginx才能执行 nginx -s stop # 中止 nginx -s quit # 退出 nginx -s reopen # 从新启动(注意不会从新读取配置文件) nginx -s reload # 从新读取配置文件
对于vue-cli建立的项目,修改vue.config.js
文件(位于项目根目录下,没有的话自行建立):webpack
module.exports = { // 开发环境中使用的端口 devServer: { port: 8001 }, // 取消生成map文件(map文件能够准确的输出是哪一行哪一列有错) productionSourceMap: false, // 开发环境和部署环境的路径 publicPath: process.env.NODE_ENV === 'production' ? '/' : '/my/', configureWebpack: (config) => { // 增长 iview-loader config.module.rules[0].use.push({ loader: 'iview-loader', options: { prefix: false } }) // 在命令行使用 vue inspect > o.js 能够检查修改后的webpack配置文件 } }
在vue项目根目录中使用命令npm run build
建立输出文件,将dist文件夹下的全部内容复制到nginx目录下的webapp/
内(没有的话自行建立)。nginx
修改nginx目录中的conf/nginx.conf
文件,在 http -> server 节点中,修改location节的内容:web
location / { root webapp; index index.html index.htm; }
在nginx根目录使用命令nginx -s reload
便可在浏览器中经过http://localhost
访问项目。vue-cli
有时一个Nginx中放了好几个子项目,须要将不一样的项目经过不一样的路径来访问。npm
对于项目1而言,修改vue.config.js
文件的publicPath
:json
publicPath: '/vue1/'
对于项目2而言,修改vue.config.js
文件的publicPath
:windows
publicPath: '/vue2/'
分别在vue项目根目录中使用命令npm run build
建立输出文件,将dist文件夹下的全部内容复制到nginx目录下的webapp/vue1
和webapp/vue2
内(没有的话自行建立)。
修改nginx目录中的conf/nginx.conf
文件,在 http -> server 节点中,修改location节的内容:
location /vue1 { root webapp; index index.html index.htm; } location /vue2 { root webapp; index index.html index.htm; }
在nginx根目录使用命令nginx -s reload
便可在浏览器中经过http://localhost/vue1
、http://localhost/vue2
访问项目一、项目2。
当先后端项目分别部署在同一台机器上时,因为没法使用相同的端口,故后端通常会将端口号设置成不一样的值(例如8080),可是当前端向后端请求资源时还要加上端口号,未免显得麻烦,故利用能够nginx将前端的指定路径代理到后端的8080端口上。
在conf/nginx.conf
文件中增长location
:
location /api { proxy_pass http://localhost:8080/api; }
这样,当前端访问/api
路径时,实际上访问的是http://localhost:8080/api
路径。