Nextjs使用Nginx未正确加载构建资产

gajydyqb  于 2023-05-06  发布在  Nginx
关注(0)|答案(1)|浏览(221)

我使用的是Nginx,下面是我的nginx配置文件

server {
  server_name my.yousico.com;

  gzip on;
  gzip_proxied any;
  gzip_types application/javascript application/x-javascript text/css text/javascript;
  gzip_comp_level 6;
  gzip_buffers 16 8k;
  gzip_min_length 256;
  client_body_buffer_size 20M;
  client_body_timeout 60s;
  client_max_body_size 20M;

  location /_next/static/ {
      alias /var/www/yousi-my/front/.next/static/;
      expires 365d;
      access_log off;
    }

  location / {
      proxy_pass http://127.0.0.1:3001;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my.yousico.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my.yousico.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
 server {
    if ($host = my.yousico.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

  listen 80;
  server_name my.yousico.com;
    return 404; # managed by Certbot

}

对于Next.js,我使用src/ folder版本。当我在本地运行我的产品构建时,所有的资产都加载得很好,但是当我用Nginx部署它时,一堆404开始出现,所以我假设我的Nginx有问题。
下面是网络选项卡x1c 0d1x的屏幕截图

mec1mxoz

mec1mxoz1#

这似乎需要让nginx将请求代理到服务器。alias有时会导致Nginx出现问题。
要修复此问题,可以尝试将alias指令替换为指向后端服务器http://localhost:3001;proxy_pass指令。
这将把/_next/static/的请求代理给服务器,服务器可以处理请求并返回静态文件。
因此,在location中将alias /var/www/yousi-my/front/.next/static/;替换为proxy_pass http://localhost:3001;可能会修复它。

...
# Other config 
 location /_next/static/ {
      # alias /var/www/yousi-my/front/.next/static/;
      proxy_pass http://localhost:3001; # <--- notice the proxy_pass here
      expires 365d;
      access_log off;  
    }
# Other config 
...

相关问题