2018 年 5 月 4 日打卡
这几天在研究 nuxt.js, 因为想重构公司的官网, 但用 vue 这个 spa 单页应用又不利于网页的 seo, 在浏览别的的博客中, 我发现了 nuxt 这个框架, 可以说完全的解决了我的问题啊.
当然本篇文章还是主要讲解记录了 vue 项目的打包, 因为我发现用 nuxt 做出来的应用无法放在服务器的二级目录下, 一定要放在根目录下, 这就让我很难受了, 网上也没有解决办法. 因为之前我用 vue 做出来的项目网上教授了放在二级根目录的方法, 所以我理所应当的把所有 vue 做出来的项目都放在了服务器的二级目录下 (现在想起来真的很蠢), 即使会出现刷新 404 的问题, 奈何本人懒, 也就不深究了.
谁能想到, 终究还是回到了 vue 项目打包上传服务器的这一步, 进过一番研究, 总算搞清楚了, 原谅我的啰嗦, 真的是难以抑制内心的激动之情, 感觉世界都清明了....._
好了, 不说了, 上教程.
首先, vue 项目使用
npm run build
来进行打包操作, 这个都知道吧
打包完成后在项目中生成一个 dist 的文件夹, 里面的内容就是咱们要传到服务器的内容了.
服务器以 ngnix 举例操作 (因为我的服务器上的环境就是 ngnix)
在服务器上找到 ngnix 的配置文件, 一般都是 default.conf
里面的内容大致是这样的
- server {
- listen 80;
- server_name localhost;
- #charset koi8-r;
- #access_log /var/log/nginx/host.access.log main;
- root /usr/share/nginx/html;
- location / {
- try_files $uri $uri//index.html;
- index index.html index.htm index.php;
- }
- error_page 404 /404.html;
- # redirect server error pages to the static page /50x.html
- #
- error_page 500 502 503 504 /50x.html;
- location = /50x.html {
- root /usr/share/nginx/html;
- }
- # proxy the PHP scripts to Apache listening on 127.0.0.1:80
- #
- #location ~ \.php$ {
- #proxy_pass http://127.0.0.1;
- #}
- # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
- #
- location ~ \.php$ {
- root /usr/share/nginx/html/;
- fastcgi_pass 127.0.0.1:9000;
- fastcgi_index index.php;
- fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
- includefastcgi_params;
- }
- # deny access to .htaccess files, if Apache's document root
- # concurs with nginx's one
- #
- #location ~ /\.ht {
- #deny all;
- #}
- }
我们需要更改我们的 ngnix 配置. 目的是配置二级子域名, 然后指向服务器的一个文件夹, 这样当我们访问子域名时, 服务器便直接指向了这个文件夹, 而不是通过 域名 + 文件名 的方式来访问 (我以前就是用这种方式, 蠢哭).
配置如下
- server
- {
- listen 80;
- server_name admin.spn365.cn;
- root /usr/share/nginx/html/sqztcAdmin;
- index index.php index.html index.htm;
- location / {
- root /usr/share/nginx/html/sqztcAdmin;
- try_files $uri $uri//index.html =404;
- }
- }
在上面的服务器默认配置的最下面再添加一个 server,server_name 后面要写你的子域名 (友情提示: 子域名要在云服务器控制台上添加解析哦),root 指向的是项目具体的文件夹, location 那个部分也很重要, 这样配置可以解决 vue 项目刷新后由于路由导致的 404 问题. 这样 ngnix 的配置就完成了.
下一步就是重启 ngnix 服务器, 让配置生效
centos 服务器上的 ngnix 的重启方法
systemctl restart nginx
ubuntu 服务器上的 ngnix 的重启方法
- sudo systemctl stop nginx
- sudo systemctl start nginx
个人使用方法, 不喜勿喷
服务器没有报错的话就是配置成功了, 现在把 dist 文件夹下的文件传到服务器上你指定的文件下试试吧. 如果没错的话, 在浏览器上访问你的子域名就能跳到你的项目了, 说太多了, 好累, 去歇着了.....
有问题欢迎留言.
来源: http://www.jianshu.com/p/f81294ab235d