使用Nginx将Vite react项目部署到Heroku

pu3pd22g  于 6个月前  发布在  Nginx
关注(0)|答案(1)|浏览(114)

我目前在尝试将我的前端Web应用程序部署到Heroku时遇到了一个挑战。这个应用程序是使用React和Vite构建的。最初,我在尝试使用最新的Heroku堆栈(堆栈22)构建它时遇到了问题,这导致我切换回Heroku堆栈20,并将heroku/nodejs buildpack与此存储库中的Heroku静态buildpack结合使用:Heroku Buildpack Static。
这个设置完美地工作了几个月,但现在,我在一个情况下,我必须升级到Heroku堆栈22,我是following the steps provided in this other thread,但它不工作。
似乎我仍然缺少一些东西,因为部署过程本身似乎是成功的。然而,当我访问部署的应用程序时,我看到的只是一个404 Not Found错误页面:x1c 0d1x
我尝试了许多不同的解决方案已经提供在这里SO,没有成功。
我删除了所有以前的buildpack并更改为https://github.com/heroku/heroku-buildpack-nginx。然后我将我的static.json文件更新为:

{
  "root": "./dist",
  "clean_urls": true,
  "routes": {
    "/**": "index.html"
  }
}

字符串
如果我理解正确的话,它指向我的root/dist文件夹。然后我运行“vite build”命令来生成一个新的dist文件夹,其中包含我构建的项目源代码。
然后我在我的根文件夹中创建了Procfile文件,并添加了这一行:web: bin/start-nginx-solo
然后我运行heroku run bash命令来生成我的nginx配置文件,它是:

daemon off;
# Heroku dynos have at least 4 cores.
worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>;

events {
    use epoll;
    accept_mutex on;
    worker_connections <%= ENV['NGINX_WORKER_CONNECTIONS'] || 1024 %>;
}

http {
    gzip on;
    gzip_comp_level 2;
    gzip_min_length 512;
    gzip_proxied any; # Heroku router sends Via header

    server_tokens off;

    log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';
    access_log <%= ENV['NGINX_ACCESS_LOG_PATH'] || 'logs/nginx/access.log' %> l2met;
    error_log <%= ENV['NGINX_ERROR_LOG_PATH'] || 'logs/nginx/error.log' %>;

    include mime.types;
    default_type application/octet-stream;
    sendfile on;

    # Must read the body in 5 seconds.
    client_body_timeout 5;

    upstream app_server {
        server unix:/tmp/nginx.socket fail_timeout=0;
    }

    server {
        listen <%= ENV["PORT"] %>;
        server_name _;
        keepalive_timeout 5;
        root /dist;

        location = /index.html {
            add_header Cache-Control "no-store, no-cache";
            try_files $uri $uri/ =404;
        }

        location / {
            add_header 'Cache-Control' "public, max-age=3600";
            try_files $uri $uri/ /index.html;
        }
    }
}


然后我创建了一个配置文件夹,并将此配置文件添加到其中,命名为nginx.conf.erb,如此处所示。
我的项目文件夹结构看起来像这样:


的数据
然后我提交并将我的更改推送到我的github存储库,它连接到Heroku,如果有新的提交,它会自动部署我的项目。然而,当我打开应用程序时,我只得到404错误。
我 * 认为 * 发生错误是因为heroku找不到我的构建文件夹与我的index.html文件,然而,我已经指定了在static.json和nginx配置文件的路径,所以我不知道我还做错了什么。

pvcm50d1

pvcm50d11#

我修复了它。以防万一其他人可能需要一些帮助,这些步骤是正确的,但我不得不再次用vite build重建我的项目并重新部署它。此外,我的.gitignore文件中列出了dist文件夹,所以我删除了它,一切顺利。愚蠢的错误。

相关问题