一、前言
最近寫的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;
}
}
這裡有個重點,我們的路徑是存放在/usr/local/nginx/html/admin,意味着,我們要在html下建立admin檔案夾,這個名稱需要跟你想要的域名路徑一緻,例如www.domain.com/admin,不然是會請求不到的,将npm run build 生成的dist目錄下的檔案copy到admin目錄去,遇到問題,可以看看nginx下logs,解決錯誤很有用的。