【问题标题】:Nginx multiple Apps on same port reverse proxy同一端口反向代理上的 Nginx 多个应用程序
【发布时间】:2022-01-07 22:50:00
【问题描述】:

我正在尝试使用 Nginx 在我的 VPS 上运行 django 应用程序和 angular 应用程序。以下是我的配置文件代码:

server {
    listen 80;
    server_name www.the-patron.com the-patron.com;
    charset utf-8;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /staticfiles/ {
        root /root/thepatron/The-Patron-Backend;
    }

    # Django Backend
    location /back/ {
        include proxy_params;
        proxy_pass http://unix:/root/thepatron/The-Patron-Backend/thepatron.sock;
    }

    # Angular Frontend
    location / {
        proxy_pass http://localhost:4200/;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_http_version 1.1;
        proxy_cache_bypass $http_upgrade;
    }
}

我的 Angular 应用程序运行良好,而 Django 应用程序却没有。如果我在第 12 行将 location /backend/ 更改为 location / 并在第 18 行将 location / 更改为 location /frontend/,那么我将让 Django 应用程序运行而 Angular 应用程序不会运行。

如何同时运行两者并更改它们的位置?

【问题讨论】:

  • 我认为完全不正确的一件事是您没有将 Angular 应用程序作为静态文件提供服务,您应该通过创建 Angular 应用程序构建并通过 ngnix 提供静态文件来做到这一点。
  • @Vipulw 我该怎么做?
  • 您应该构建您的 Angular 应用程序并提供静态文件。此外,如果您的 Django 后端在端口号上运行,则需要使用上述用于 Angular 的配置

标签: nginx nginx-reverse-proxy nginx-config nginx-location


【解决方案1】:

因为我之前分别托管 Angular 和 Django 应用程序的方法是完全错误的。感谢上面@Vipulw的cmets,我终于设法解决了我的问题。

对我有用的是,我将我的 Angular 应用程序构建到生产环境,并将生成的构建文件夹放在我的 Django 应用程序目录中的我的静态文件文件夹中,然后配置我的 Nginx 以服务于该 Angular构建。

下面是我的新Nginx 配置文件:

# Angular Reverse Proxy
server {
    listen 80;
    server_name <Domain name or IP address>;


    root /root/<path to Django app>/static/<Angular app build folder>;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
 }
}

# Django Reverse Proxy
server {
    listen 8080;
    server_name <Domain name or IP address>;

    location / {
        include proxy_params;
        proxy_pass http://unix:/root/<path to Django app>/<myapp>.sock;
    }
}

补充说明:

通过上面提到的这种方式,我的Angular 应用程序在port 80 上运行,而我的Django 应用程序在port 8080 上运行。这种方式一切正常,但我不认为这是同时运行Angular 和Django 的最佳方式。经过一番研究,我发现在one app 中服务Angular and Django 的最佳方式是让默认的Django 路由指向Angular 构建。现在默认的Django 路由指向Django Rest Framework root directory。

很遗憾,我现在不知道如何让Django's default route 指向Angular build file。

【讨论】:

    猜你喜欢
    • 2017-02-07
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2020-09-05
    • 1970-01-01
    • 2020-03-13
    相关资源
    最近更新 更多