一、前言
最近寫的vue項目,通過nginx部署,並且需要部署在nginx下的子目錄,就是非html根目錄。如果是部署在根目錄,就比較簡單了,但是部署在子目錄,就踩了不少坑。
Linux安裝Nginx詳細教程可以看這篇:https://baijiahao.baidu.com/s?id=1659582871769773387&wfr=spider&for=pc
Nginx配置文件詳解可以看這篇:https://www.cnblogs.com/hunttown/p/5759959.html
千萬使用window版的Nginx去測試,很容易出現錯誤的。
二、配置
我們想要的效果是,比如域名是www.domain.com,我們的項目是配置在www.domain.com/admin 上,
1、vue項目的vue.config.js,publicPath設置為/admin/
module.exports = { publicPath: '/admin/', assetsDir: 'static', productionSourceMap: false, }
2、router/index.js ,base設置為admin
import Vue from 'vue'; import Router from 'vue-router'; Vue.use(Router); export default new Router({ mode: "history", base: "admin", routes: [...] });
3、配置nginx.conf
server { listen 8080; server_name localhost; client_max_body_size 200m; location ~ \.(html|css|js|gif|jpg|jpeg|png|ttf|woff|ico|pdf|block|mp3)$ { root html; index index.html index.htm; } location / { root '/usr/local/nginx/html/admin'; index index.html index.htm; try_files $uri $uri/ @router; add_header Cache-Control no-cache; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Credentials *; add_header Access-Control-Allow-Methods *; add_header Access-Control-Allow-Headers *; } location @router{ rewrite ^.*$ /admin/index.html last; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }
}