angular - 如何配置 nginx 以在/和代理/api 上为另一个 api 服务器提供 Angular 应用程序?

标签 angular nginx proxy reverse-proxy

我正在尝试配置一个 nginx Docker 容器,以在其根路径(目前有效)上为 Angular 应用程序提供服务,并通过/api 上的代理使后端可用。

我已经阅读了 Stackoverflow 和一些博客上的多个线程,但到目前为止没有任何配置有效。如果我在/上调用我的应用程序,Angular 应用程序就可以运行。当我尝试在同一个 url 上调用/api 时,它被重定向到/并且没有显示任何内容——我猜 Angular 路由器有一些它无法处理的路由。但是 Nginx 应该在调用 Angular 应用程序之前捕获该路由。我该怎么做?

我不确定哪里出了问题。你看到我的配置中的错误了吗?

server {
  listen 80;
  sendfile on;
  default_type application/octet-stream;

  gzip on;
  gzip_http_version 1.1;
  gzip_disable      "MSIE [1-6]\.";
  gzip_min_length   256;
  gzip_vary         on;
  gzip_proxied      expired no-cache no-store private auth;
  gzip_types        text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  gzip_comp_level   9;

  location / {
    root /usr/share/nginx/html;
    try_files $uri $uri/ /index.html =404;
  }
  
  location /api/ {
    proxy_pass http://host.docker.internal:8080/api/;
    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;
  }
}

Edit1:我发现了一个问题:容器无法到达 api-server。我在配置中将其更改为 host.docker.internal,可通过 docker ci 访问。但是我仍然无法在 nginx 容器上调用/api。我现在收到 404。

最佳答案

我会使用下面的语法让 Nginx 知道这是在您的通用位置 location/ 之前。

location ^~ /api/ { }

您可以在此处阅读更多信息 -> https://www.journaldev.com/26342/nginx-location-directive

关于angular - 如何配置 nginx 以在/和代理/api 上为另一个 api 服务器提供 Angular 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70864008/

相关文章:

javascript - Angular2 - 防止 ngOnDestroy 发生

node.js - Nginx 反向代理不适用于域名

ruby - 阻止或重定向请求到 Selenium 中的特定路径或域

security - 反向代理和网关有什么区别?

javascript - 为什么 RxJS subscribe 允许省略箭头函数和下面的方法参数?

angular - pathType.isDirectory 中的错误不是函数

javascript - 删除特定项目(索引)方法

Azure kubernetes - Nginx Controller 的数量?

python - header 中返回的内容长度,用于使用 nginx、uwsgi 和 Flask 进行分块传输编码

java - 如何使用 javassist/CGLib 修改/装饰从第 3 方 API 返回的对象