Linux安装 nignx +部署 vue 项目

676 阅读2分钟

一、安装 nignx

第一步 安装依赖

  1. 安装 gcc

    编译 nginx 源码需要 gcc 环境。

    yum install gcc-c++
    
  2. 安装 pcre

    nginx 的 Rewrite 模块和 HTTP 核心模块会使用到 PCRE 正则表达式语法。这里需要安装 pcre 和 pcre-devel,第一个安装包提供编译版本的库,而第二个提供开发阶段的头文件和编译项目的源代码。

    yum install -y pcre pcre-devel
    
  3. 安装 zlib

    zlib 库提供了开发人员的压缩算法,在 nginx 的各种模块中需要使用 gzip 压缩。

    yum install -y zlib zlib-devel
    
  4. 安装 openssl

    nginx 不仅支持 http 协议,还支持 https,如果使用了 https,需要安装 OpenSSL 库。

    yum install -y openssl openssl-devel
    

(一键安装 yum -y install gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel

第二步 下载并解压安装包

  1. 可以去官网下载,也可以使用 wget 命令下载,一般是把压缩包放到 /usr/local/src 目录下。

    wget http://nginx.org/download/nginx-XXX.tar.gz 
    
  2. 解压,进入 nginx-XXX 目录,进行配置。注意编译后的文件都放在 /usr/local/nginx

    tar -xvf nginx-XXX.tar.gz
    cd nginx-XXX
    ./configure
    

    1.png 2.png

  3. 编译,安装。

    make
    make install
    

第三步 启动测试

  1. 启动

    /usr/local/nginx/sbin/nginx
    
  2. 在浏览器中输入 IP ,如下图所示,则表示安装成功。

    3.png

  3. 如果无法访问,则关闭防火墙。

    • 关闭防火墙:systemctl stop firewalld.service
    • 禁用防火墙:systemctl disable firewalld.service
  4. 常用命令(在安装目录中 /usr/local/nginx/sbin

    • 重启:./nginx –s reload
    • 关闭:./nginx –s stop
    • 强制关闭: pkill nginx
    • 检查配置文件合法性: ./nginx –t
  5. nginx.conf 配置文件,仅部分设置,详细请自行查询。

    4.png 5.png

二、部署 vue 项目

第一步 配置 nginx.conf

  1. nginx.conf 文件在 nginx/conf/ 目录下。端口可任意设置。在 location 中,root 是设置 dist 包的路径(默认使用相对路径 html/ 下,也可以使用绝对路径);try_files 是处理 history 路由模式下页面404的问题,在 hash 模式下可不设置;proxy_pass 设置代理转发,结尾有无 / 可参考这篇文章。每次修改配置文件后,都需要重启 nginx 才能生效。

    7.png

第二步 打包 dist 并部署

  1. vue 项目默认 hash 模式路由,在 vue.config.js 设置 publicPath,然后生成 dist 包并压缩。

    6.png

  2. 将 dist.zip 上传至 location 中 root 设置目录下,然后解压。

  3. 系统默认使用 ip 访问项目.若想使用域名访问,需要在 nginx.conf 中设置 server_name,同时在本机 C:\Windows\System32\drivers\etc\hosts 文件中设置 DNS。

    8.png

  4. 访问测试

    11.png 12.png

附:参考文章