加油
努力

Alibaba Cloud Linux 3.2104 LTS环境下如何配置Nginx托管Vue项目?

在 Alibaba Cloud Linux 3.2104 LTS(基于 RHEL 8/CentOS 8 兼容内核,使用 dnf 包管理器)环境下配置 Nginx 托管 Vue 项目(生产构建的静态站点),需按以下安全、规范、可维护的步骤操作。假设你已有一个构建完成的 Vue 项目(dist/ 目录)。


✅ 前提条件

  • 已安装并启用 nginx(Alibaba Cloud Linux 3 默认源已包含)
  • Vue 项目已执行 npm run build(或 yarn build),生成 dist/ 目录(含 index.html, assets/ 等)
  • 推荐以非 root 用户(如 deploy)管理前端文件,Nginx 以 nginx 用户运行

🛠️ 完整配置步骤

1️⃣ 安装并启动 Nginx

# 更新系统(可选但推荐)
sudo dnf update -y

# 安装 nginx(Alibaba Cloud Linux 3 默认启用 aliyun-repo,无需额外配置)
sudo dnf install -y nginx

# 启动并设置开机自启
sudo systemctl enable nginx
sudo systemctl start nginx

# 验证状态
sudo systemctl status nginx

✅ 防火墙说明:Alibaba Cloud Linux 3 默认使用 firewalld
若需公网访问,放行 HTTP/HTTPS:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

2️⃣ 准备 Vue 项目静态文件(推荐路径与权限)

# 创建专用目录(避免混用 /usr/share/nginx/html)
sudo mkdir -p /var/www/my-vue-app

# 将你的 dist 内容复制进去(示例:本地构建后上传)
# 假设你已通过 scp 或 ossutil 上传 dist/ 到 /tmp/dist/
sudo cp -r /tmp/dist/* /var/www/my-vue-app/

# 设置正确所有权和权限(nginx 用户需有读取权限)
sudo chown -R root:nginx /var/www/my-vue-app
sudo chmod -R 755 /var/www/my-vue-app
sudo chmod 644 /var/www/my-vue-app/index.html

⚠️ 注意:Vue Router 使用 history 模式时,需 Nginx 支持 HTML5 History fallback(见第4步)


3️⃣ 创建独立的 Nginx Server 配置(推荐,不修改默认 default.conf)

sudo vim /etc/nginx/conf.d/my-vue-app.conf

配置内容(支持 history 路由 + gzip + 安全头)

server {
    listen       80;
    server_name  your-domain.com;  # 👈 替换为你的域名或 IP(测试可用 _ 或 localhost)
    root         /var/www/my-vue-app;
    index        index.html;

    # 关键:支持 Vue Router history 模式 —— 所有非资源请求回退到 index.html
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 静态资源缓存优化(js/css/img/fonts)
    location ~* .(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # 禁止访问敏感文件
    location ~ /.ht {
        deny all;
    }

    # 可选:启用 Gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # 可选:添加安全响应头(增强防护)
    add_header X-Frame-Options "DENY" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;" always;
}

🔍 验证配置语法:

sudo nginx -t

✅ 输出 syntax is oktest is successful 即可。


4️⃣ 重载 Nginx 生效配置

sudo systemctl reload nginx
# 或
sudo nginx -s reload

5️⃣ (可选)配置 HTTPS(强烈推荐生产环境)

使用 Alibaba Cloud SSL 证书或 Let’s Encrypt(推荐 certbot):

# 安装 certbot(EPEL 源)
sudo dnf install -y epel-release
sudo dnf install -y python3-certbot-nginx

# 自动申请并配置 HTTPS(需域名已解析到该服务器)
sudo certbot --nginx -d your-domain.com

# 自动续期已由 systemd timer 启用(检查:`sudo systemctl list-timers | grep certbot`)

✅ 启用 HTTPS 后,my-vue-app.conf 中会自动添加 listen 443 ssl 块,并重定向 HTTP → HTTPS。


6️⃣ (可选)Vue 项目构建注意事项(确保兼容性)

  • vue.config.js 中设置正确的 publicPath(尤其部署在子路径时):
    // vue.config.js
    module.exports = {
    publicPath: process.env.NODE_ENV === 'production'
      ? '/'  // 根路径部署(推荐)
      // : '/subpath/'  // 若需部署在 /subpath/ 下,则此处设为 '/subpath/',且 Nginx root 保持不变,location 改为 location /subpath/
      : '/'
    }
  • 若部署在子路径(如 https://example.com/app/),则 Nginx 配置需调整:
    location /app/ {
      alias /var/www/my-vue-app/;
      try_files $uri $uri/ /app/index.html;
    }

    注意:alias 结尾需带 /root 不适用此场景。


✅ 验证访问

  • 浏览器打开:http://your-server-iphttp://your-domain.com
  • 打开开发者工具 → Network,确认:
    • index.html 返回 200
    • assets/*.js 等返回 200
    • 切换路由(如 /about)不报 404 → ✅ history fallback 生效

🧩 故障排查常见问题

现象 原因 解决
403 Forbidden 文件权限不足(nginx 用户无法读取) sudo chown -R root:nginx /var/www/my-vue-app && sudo chmod -R 755
404 on /xxx (history 路由) try_files 未配置或位置错误 确保 location / { try_files ... } 存在且无更高优先级 location 冲突
页面空白,控制台报 Failed to load resource: net::ERR_ABORTED publicPath 错误导致 JS/CSS 路径 404 检查 dist/index.html<script src="/js/app.xxx.js"> 路径是否可访问;修正 vue.config.js
Nginx 启动失败 配置语法错误或端口被占用 sudo nginx -t + sudo ss -tuln | grep ':80'

✅ 最佳实践总结

  • ✅ 使用独立 conf.d/*.conf 文件,而非修改 default.conf
  • ✅ 静态文件存放于 /var/www/(语义清晰,SELinux 友好)
  • ✅ 启用 HTTPS + HTTP 自动跳转(安全合规)
  • ✅ 启用 gzip 和静态资源长缓存(提升性能)
  • ✅ 添加基础安全响应头(防 XSS/点击劫持等)
  • ✅ Vue 构建前确认 publicPath 与部署路径一致

如需进一步支持(如:配合 PM2 托管 SSR、Nginx 反向X_X后端 API、CI/CD 自动部署脚本、SELinux 策略适配),欢迎继续提问!🚀

云服务器