【问题标题】:Nginx NodeJS proxying + AngularJS index.html rewritingNginx NodeJS 代理 + AngularJS index.html 重写
【发布时间】:2017-08-28 14:30:05
【问题描述】:

我有一个基于 NodeJS + Express / AngularJS 的 webapp。

AngularJS $routeProvider 处于 html5 模式,这意味着 URL 中没有 index.html 和 #。

我想用 nginx 来:

  • 代理 /api 到我的 NodeJS 应用程序
  • /中的所有请求重定向到/index.html
  • /app中的所有请求重定向到/app/index.html

示例

  • /support/ 应该重写为index.html,然后 angular $routeProvider 处理support 路由并渲染SupportController
  • /app/login/app/ 应该重写为/app/index.html,然后角度$routeProvider 处理login 路由并渲染LoginController
  • /api/auth/login/api/* 应该始终被代理重定向到 http://localhost:3000/,因为在 /api 下没有静态文件可服务

约束

问题是,使用类似这样的东西重定向到 API:

location / {
  try_files $uri @backend;
}

不兼容 AngularJS 的 index.html 重写:

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

location /app/ {
  try_files $uri $uri/ /app/index.html =404;
}

如果我指定/api 位置,Nginx 会用/ 位置覆盖它...

我可以在这里做什么?

【问题讨论】:

  • 你为什么在$之前是\\ ?他们不需要
  • 是的,我删除了它们,因为我从我的 bash 脚本中复制,所以需要在其中转义

标签: angularjs node.js nginx


【解决方案1】:

我认为这应该是一个简单的配置

location / {
   try_files /index.html =555;
}

location /app/ {
  try_files /app/index.html =666;
}

location /api/ {
   proxy_pass http://nodeip:3000/;
}

如果你的解释是正确的,那么上面的配置应该做

【讨论】:

  • 是的,但我说我需要将每个请求(如 /support/app/login)重写为 index.html 文件...在 angularjs 上使用 html5 模式
  • 添加一些确切的网址以及您对问题的期望。也请添加参数,所以我明白了
  • @SherlockStd,需要一些时间来更好地理解这一点。几天后会回复你。看看到时候你能不能自己解决,或者其他人来解决
  • 已经解决了,请看下面我的回答 :) 感谢一切!
【解决方案2】:

我找到了正确的配置,我想我在发布之前测试了它,但是由于 nginx 在 http://locahost:3000/api/login/auth 而不是 http://locahost:3000/login/auth 上重定向 https://example.com/api/login/auth,我从 Express 得到 404,所以我认为它们来自 Nginx。 ..我只是“像愚蠢一样愚蠢”......

感谢您的帮助塔伦!

这是一个很好的配置(非常基本):

location /api {
  proxy_set_header  Host \$host;
  proxy_set_header  X-Real-IP \$remote_addr;
  proxy_set_header  X-Forwarded-For \$proxy_add_x_forwarded_for;
  proxy_set_header  X-Forwarded-Proto \$scheme;

  # Fix the “It appears that your reverse proxy set up is broken" error.
  proxy_pass          http://localhost:3000;
  proxy_read_timeout  90;

  proxy_redirect      http://localhost:3000 https://example.com/api/;
}

location / {
  try_files \$uri \$uri/ /index.html =404;
}

location /app/ {
  try_files \$uri \$uri/ /app/index.html =404;
}

【讨论】:

    猜你喜欢
    • 2013-05-08
    • 2014-03-12
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多