在Nginx上部署vue项目(Mac版)

构建项目

将vue项目打包,打包后会在项目根路径下生成一个dist文件,这个就是需要发布到nginx服务器上的静态页面。(不同项目配置的打包命令可能稍有不同)

$ npm run dev

安装Nginx

1、打开terminal终端

2、安装Command Line Tools

$ xcode-select --install

3、安装brew命令

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

4、安装nginx

$ brew install nginx

5、查看版本

$ nginx -v

6、启动nginx

$ sudo nginx

7、重新加载配置/重启/停止/退出nginx

$ sudo nginx -s reload | reopen | stop | quit

配置Nginx

配置nginx.conf来设置端口和映射路径,使项目在nginx上跑起来。

1、打开nginx.conf文件。一般该文件在/usr/local/etc/nginx/路径下,可通过“访达”->“前往文件夹”打开。

2、设置访问权限;设置监听端口和地址;设置非根路径项目地址。权限设置不对,会报403错误。端口建议设为默认的80,否则访问网址时需要手动带上端口,且会出现跨域问题。

注:Nginx路径配置取决于项目结构和项目中对URL的配置,这里一个域名下有多个项目,所以没用根路径配置,而是在根路径下指定了一层路径/x。项目的访问地址:http://aaa.bbb.com/x/#/login,对应的配置如下:

user  root wheel;    # 设置访问权限
worker_processes  1;

...

    server {
        listen       80;    # 设置监听端口
        server_name  localhost;    # 设置监听域名

...

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

...

        location ^~ /x {
            alias /Users/carrie/Documents/Workspace/x/dist;    # 项目打包后静态文件所在路径
            add_header Cache-Control no-store;
            #proxy_set_header Host $host:8080;
            break;
        }

        location ^~ /mockApi {
           proxy_pass  http://test:20910/mock;
           proxy_hide_header Access-Control-Allow-Origin;
           add_header Access-Control-Allow-Credentials true;
           add_header Access-Control-Allow-Headers Origin,Authorization,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Content-Type;
           add_header Access-Control-Allow-Methods GET,POST,PUT,OPTIONS;
           add_header Access-Control-Allow-Origin http://localhost:8080;
        }

...

}

3、项目中对域名做了设定,所以要在hosts文件里,关联本机IP和设定的域名“aaa.bbb.com”。“访达”->“前往文件夹”,输入/private/etc/,打开文件夹下的hosts文件,作如下配置:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1	aaa.bbb.com
255.255.255.255	broadcasthost
::1             localhost

运行项目

1、启动Nginx

$ sudo nginx

2、构建项目

$ npm install    # 第一次构建要安装依赖
$ npm run dev

访问本地项目地址:http://aaa.bbb.com/x/#/login

猜你喜欢

转载自blog.csdn.net/mocoe/article/details/83932268