如何在Nginx上手动部署Angular 18 SSR

问题描述 投票:0回答:1

我已经构建了项目 home-aap,并启用了 Angular 18 和 SSR。现在 Angular 18 内置了 SSR,因此执行 ng build 后它生成了以下文件夹: [在此输入图像描述][1]

/var/www/dist/home-app/浏览器

/var/www/dist/home-app/server

以下是 Nginx 的主配置:

server {
    listen 80;
    server_name localhost; # Change to your domain

    # Serve static files directly from the browser build
    location / {
        root /var/www/dist/home-app/browser; # Adjust to your actual path
        try_files $uri $uri/ /index.html; # Fallback to index.html for SPA
    }

    # Serve dynamic SSR content for specific routes
    location /ssr {
        proxy_pass http://localhost:4000; # Node server
        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;
    }
}

以上已成功链接到启用站点的文件夹中: [在此输入图像描述][2]

此外,server.mjs 正在 localhost:4000 上运行: [在此输入图像描述][3]

因此,如果我访问 localhost,Nginx 会抛出 403: [在此输入图像描述][4] 但如果我访问 http://localhost:4000/,应用程序加载成功: [在此输入图像描述][5]

但是为什么它没有在本地主机上加载。 我查看了 Angular 官方页面,但关于在服务器或 VPS 上手动部署的内容并不多。 https://angular.dev/tools/cli/deployment

如果有人能建议如何在服务器/VPS 上的 Nginx 上手动激活 SSR 来正确部署 Angular 18,那将会非常有帮助。

提前致谢。 [1]:https://i.sstatic.net/BOF3LDRz.png [2]:https://i.sstatic.net/lQKzVbf9.png [3]:https://i.sstatic.net/jtDJYl5F.png [4]:https://i.sstatic.net/26x62XzM.png [5]:https://i.sstatic.net/CNjjQlrk.png

angular nginx deployment vps dev-to-production
1个回答
0
投票

我找到了解决办法,在Angular 18 dist/browser文件夹中包含index.csr.html而不是index.html,所以我们必须相应地conf文件Nginx。

下面是 home-app.conf 的更新代码

server {
    listen 80;
    server_name localhost;

    # Serve static files for CSR
    location / {
        root /var/www/dist/home-app/browser;
        index index.csr.html;  # Set index.csr.html as the default index file
        try_files $uri $uri/ /index.csr.html;  # Fallback to index.csr.html for CSR
    }

    # Serve dynamic SSR content for specific routes
    location /ssr {
        proxy_pass http://localhost:4000;  # Forward requests to your Node.js SSR server
        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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.