You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Elastic Beanstalk中隐藏/var/app/current目录的源代码?

在Elastic Beanstalk Node.js平台隐藏React源代码的解决方案

核心问题梳理

你部署的是create-react-app默认项目,已添加GENERATE_SOURCEMAP=false但仍能在浏览器审查元素中看到源码,且/var/app/current目录暴露。以下是针对性解决步骤:


1. 只部署构建产物,禁止源码上传

create-react-app的编译产物在build/目录,Elastic Beanstalk(EB)默认会同步整个项目目录,导致源码被上传到服务器。需做以下配置:

  • 修改package.json的脚本,指定生产环境用静态文件服务启动:
    "scripts": {
      "start": "serve -s build",
      "build": "GENERATE_SOURCEMAP=false react-scripts build",
      "dev": "react-scripts start"
    }
    
  • 安装静态服务依赖:npm install --save serve
  • 创建.ebignore文件,排除源码目录和无关文件,确保EB只上传必要文件:
    node_modules/
    src/
    public/
    .git/
    .env
    .gitignore
    

2. 自定义Nginx配置,阻止服务器目录访问

EB的Node.js平台用Nginx反向代理,默认配置可能允许访问服务器根目录文件。需覆盖默认配置:

  • 在项目根目录创建.ebextensions/nginx/conf.d/custom.conf文件,添加以下规则:
    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    # 强制从build目录提供静态资源,禁止访问上级目录
    location / {
        root /var/app/current/build;
        try_files $uri $uri/ /index.html;
        deny /../;
    }
    
    # 直接阻止访问/var/app/current路径
    location ~ ^/var/app/current/ {
        deny all;
    }
    

3. 验证部署效果

  • 本地先执行npm run build,检查build/目录下是否存在.map文件(GENERATE_SOURCEMAP=false生效的话不会生成)
  • 部署到EB后,登录EC2实例检查/var/app/current目录,确认只有build/、package.json、node_modules,无src/、public/等源码目录
  • 浏览器打开应用,进入审查元素的Sources标签,确认仅能看到压缩后的js/css文件,无React源码

4. 可选:改用EB静态文件服务模式

若无需Node.js服务,可直接配置EB为静态文件服务器,进一步简化部署:

  • 创建.ebextensions/static-files.config文件:
    option_settings:
      aws:elasticbeanstalk:environment:proxy:
        StaticFiles: "/static/=build/static/"
      aws:elasticbeanstalk:container:nodejs:
        NodeCommand: "node -e 'console.log(\"Static server running\")'"
    

内容的提问来源于stack exchange,提问作者Gerardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:15:13