nginx 部署微服务前端

安装 Nginx

系统要求

本文档基于 CentOS 系统,其他 Linux 发行版请参考相应的包管理器命令。

配置 Nginx 仓库

创建 Nginx 仓库配置文件:

vim /etc/yum.repos.d/nginx.repo

添加以下内容:

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

安装 Nginx

# 启用 mainline 仓库
sudo yum-config-manager --enable nginx-mainline

# 安装 Nginx
sudo yum install nginx

配置 Nginx

创建 PIGX 前端配置文件:

vim /etc/nginx/conf.d/pigx-ui.conf

添加以下配置:

server {
  listen 80;
  server_name localhost;

  # Gzip 压缩配置
  gzip on;
  gzip_static on;
  gzip_min_length 1k;
  gzip_comp_level 4;
  gzip_proxied any;
  gzip_types text/plain text/xml text/css application/javascript;
  gzip_vary on;
  gzip_http_version 1.0;
  gzip_disable "MSIE [1-6].(?!.*SV1)";

  # 前端静态文件目录
  root /data/pigx-ui/;

  # API 代理配置
  location ^~/api/ {
    proxy_pass http://127.0.0.1:9999/;
    proxy_connect_timeout 60s;
    proxy_read_timeout 120s;
    proxy_send_timeout 120s;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto http;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $http_host;
  }

  # 安全防护:屏蔽敏感路径
  location ~* ^/(actuator|swagger-ui|v3/api-docs|swagger-resources|webjars|doc.html|druid) {
    return 403;
  }
}
配置说明
  • proxy_pass 后的斜杠 / 不可省略,它会将 /api/ 前缀从请求路径中移除
  • 请根据实际部署修改 proxy_pass 地址和端口
  • 敏感路径屏蔽配置可防止生产环境暴露 Swagger 等调试接口

构建前端

在前端项目根目录执行构建命令:

npm run build
部署步骤

构建完成后,将 dist 目录下的所有文件上传到 Nginx 配置中指定的 /data/pigx-ui/ 目录。

启动服务

# 测试配置文件
sudo nginx -t

# 启动 Nginx
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx