美文网首页
从零开始 Nginx 部署 Vue2 Router histor

从零开始 Nginx 部署 Vue2 Router histor

作者: 29cd8e532f17 | 来源:发表于2018-12-14 19:01 被阅读94次

本篇的环境:(以本篇为例 但是不局限于本篇 没有的小伙伴自行安装)

  1. NodeJs 8.12.0 (10以下)
  2. Npm 5.6.0
  3. Vue脚手架
  4. webpack 4.16.0
  5. 服务器端 nginx (CentOS Linux release 7.4.1708 (Core)) (nginx~1.13.7)

使用vue脚手架生成一个新鲜的vue2项目

这里我们给项目起名为 vue-history , 创建时候未使用ESLint、e2e以及测试单元

如果碰到 downloading template 过慢时候可先使用 cnpm install --save-dev webpack 安装webpack后在进行脚手架安装 (我安装的时候就特别慢 - -!)

$  vue init webpack vue-history  ($后面是对应的指令 复制时请不要复制$)


? Project name vue-history
? Project description A Vue.js project
? Author xxx <xxx@qq.com>
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) npm

   vue-cli · Generated "vue-history".


# Installing project dependencies ...
# ========================

npm WARN deprecated browserslist@2.11.3: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm WARN deprecated bfj-node4@5.3.1: Switch to the `bfj` package for fixes and new features!
npm WARN deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.

> fsevents@1.2.4 install /Users/xxx/Desktop/vue-history/node_modules/fsevents
> node install

[fsevents] Success: "/Users/xxx/Desktop/vue-history/node_modules/fsevents/lib/binding/Release/node-v57-darwin-x64/fse.node" already installed
Pass --update-binary to reinstall or --build-from-source to recompile

> uglifyjs-webpack-plugin@0.4.6 postinstall /Users/xxx/Desktop/vue-history/node_modules/webpack/node_modules/uglifyjs-webpack-plugin
> node lib/post_install.js

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN ajv-keywords@3.2.0 requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.

added 1195 packages in 30.47s

# Project initialization finished!
# ========================

To get started:

  cd vue-history
  npm run dev

Documentation can be found at https://vuejs-templates.github.io/webpack

在 src/components 目录下创建Page1.vue和Page2.vue 两个页面

//Page1.vue

<template>
  <div class="page1">
    我是page1~~
  </div>
</template>

<script>
  export default {
    name: 'page1',
    data() {

    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

//Page2.vue

<template>
  <div class="page2">
    我是page2~~
  </div>
</template>

<script>
  export default {
    name: 'page1',
    data() {

    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

修改 src/router/index.js

配置好刚才的两个页面以及开启history模式

设置 base 为 /vue-history/dist/

//router

import Vue from 'vue'
import Router from 'vue-router'
import Page1 from '@/components/Page1'
import Page2 from '@/components/Page2'

Vue.use(Router)

export default new Router({
  mode: 'history',
  base: '/vue-history/dist/',
  routes: [
    {
      path:"/",
      redirect:"/page1"
    },
    {
      path: '/page1',
      name: 'page1',
      component: Page1
    },
    {
      path: '/page2',
      name: 'page2',
      component: Page2
    }
  ]
})

修改 config/index.js

build 下 assetsPublicPath 为 /vue-history/dist/

//config

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-


    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: ' /vue-history/dist/',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

使用npm进行打包

$ npm run build


> vue-history@1.0.0 build /Users/xxx/Desktop/vue-history
> node build/build.js

Hash: 9983cffbfd659f7b61f4
Version: webpack 3.12.0
Time: 6256ms
                                                  Asset       Size  Chunks             Chunk Names
                  static/js/app.f2849b8e8e17ec915ffd.js    10.5 kB       0  [emitted]  app
               static/js/vendor.20d54e752692d648b42a.js     113 kB       1  [emitted]  vendor
             static/js/manifest.ccf7580add779bd36cc3.js  875 bytes       2  [emitted]  manifest
    static/css/app.ac154d931b685da0b7d2d369888411d5.css  237 bytes       0  [emitted]  app
static/css/app.ac154d931b685da0b7d2d369888411d5.css.map  517 bytes          [emitted]  
              static/js/app.f2849b8e8e17ec915ffd.js.map    20.9 kB       0  [emitted]  app
           static/js/vendor.20d54e752692d648b42a.js.map     560 kB       1  [emitted]  vendor
         static/js/manifest.ccf7580add779bd36cc3.js.map    4.99 kB       2  [emitted]  manifest
                                             index.html  581 bytes          [emitted]  

  Build complete.

  Tip: built files are meant to be served over an HTTP server.
  Opening index.html over file:// won't work.

打包完毕 上传到服务器的nginx下html目录下
html目录下创建vue-history文件夹 把刚打包好的 dist文件夹 放入

服务器端设置

进入到nginx根目录(笔者的在/usr/local/nginx/)

修改 config/nginx.config 文件 添加重定向配置

本篇在server 80端口下添加如下配置

add_header                  Set-Cookie "HttpOnly";
add_header                  Set-Cookie "Secure";
add_header                  X-Frame-Options "SAMEORIGIN";
location @router { 
rewrite ^.*$ /vue-history/dist/index.html last; 
}
location /vue-history/dist/{    
try_files $uri $uri/ @router;    
index index.html; 
} 

文件全部内容如下

#nginx.config

user  root;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        root /usr/local/nginx/html/;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            try_files $uri $uri/ dist/index.html;
        }

        #vue history配置
        add_header                  Set-Cookie "HttpOnly";
        add_header                  Set-Cookie "Secure";
        add_header                  X-Frame-Options "SAMEORIGIN";
        location @router { 
                  rewrite ^.*$ /vue-history/dist/index.html last; 
                }
                location /vue-history/dist/{    
                    try_files $uri $uri/ @router;    
                    index index.html; 
                } 

        #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   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           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

保存完毕 重启nginx 服务器

使用

http://{{域名或者ip}}/vue-history/dist/page1
或
http://{{域名或者ip}}/vue-history/dist/page2

访问网址 页面出现刚才配置的内容

相关文章

网友评论

      本文标题:从零开始 Nginx 部署 Vue2 Router histor

      本文链接:https://www.haomeiwen.com/subject/xnfnhqtx.html