【问题标题】:proxy_pass from wildcard subdomain via NGINXproxy_pass 从通配符子域通过 NGINX
【发布时间】:2020-02-21 11:44:59
【问题描述】:

我正在尝试向访问通配符子域的用户显示子文件夹: abc.example.com -> example.com/xyz

这个 NGINX 服务器块代码正在运行:

server {
   # server name with regexp
   server_name ~^(?<sub>[^.]+)\.example\.com$;
   # this server catches all requests to xxxx.example.com
   # and put "xxxx" to $sub variable
   location / {
        # finally we want to request different URI from remote server
        proxy_pass http://localhost:8000;
        # proxy_redirect will rewrite Location: header from backend
        # or you can leave proxy_redirect off;
        proxy_redirect http://localhost:8000 http://$sub.localhost:8000;
   }
[certbot code]
}

(发现问题5249883)。

但是当用“https:localhost:8000/xyz”替换proxy_pass值“https://localhost:8000”时,我得到这些错误和一个空白页:

Uncaught SyntaxError: Unexpected token '<'

socket.io.js 和commons.js 中。

我在 example.com 上运行的应用是使用 React/Gatsby 构建的。 example.com/demo 正在运行。

编辑:我输入了错误的错误信息,当我尝试不同的东西时出现了这些错误。

【问题讨论】:

  • 尝试https://localhost:8000/xyz/ 而不是https://localhost:8000/xyz
  • @IvanShatsky 我得到了同样的结果
  • 我认为您遇到了我试图描述的问题here
  • 这两个资产的正确 URL 是什么?例如。他们是/xyz/socket.io.js 还是/socket.io.js
  • @IvanShatsky 感谢您的链接!例如,我使用 /api 的位置前缀,效果很好。我尝试在此博客中设置位置前缀,但随后获得了放入 /var/[domain]/html 目录的示例 html 页面。这是为什么?除此之外,如果我使用位置前缀,那不是只是将我的主应用程序从“/”移动到“/someDirectory”,而我仍然必须使用 location_pass 来访问我的子文件夹吗?我不确定您是否看到我关于错误的更新。看来,服务器为 socket.io.js 提供了 html 而不是 js (?)。你知道为什么吗?

标签: reactjs nginx server config gatsby


【解决方案1】:

问题是(据我现在理解),Gatsby 在 example.com/[script-address] 托管脚本并使用 NGINX proxy_pass,脚本地址也更改为 example.com/[subfolder]/[script -地址]。

解决方案是在gatsby.config 中设置“路径前缀”值,如下所述:Gatsby documentation

通过这样做,我为我的完整应用程序设置了一个前缀,这并不是我真正想要做的,因为主应用程序仍然托管在 example.com 上,我只希望将子域传递给一些子页面。 (子域由用户创建并由主应用程序动态提供)。 令人惊讶的是,更改路径前缀后,(主应用程序和子域)都可以正常工作。

这似乎只适用于生产构建(您必须在构建时传递一个标志),所以我目前仍然不确定在开发时要做什么。

如果您知道如何更好地解决这个问题,请给我发消息 :)

感谢 Ivan 和 Richard 让我走上正轨!

编辑:资产前缀会是更好的方法:https://www.gatsbyjs.org/docs/asset-prefix/ 它仍然很难看,我认为有办法通过 NGINX 解决这个问题。 我仍然不能以这种方式使用开发版本。

编辑 2: 在我已经搞砸了 3 天之后,我再次尝试找到类似的问题并且很幸运:https://serverfault.com/questions/840654/nginx-map-subdomain-to-a-subdirectory-on-proxied-server 我已将代码更改为:

    location    / {
    proxy_pass http://localhost:8000/xyz$uri/;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;

   }

终于成功了:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 2019-03-18
    • 2014-09-06
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 2014-06-11
    • 2020-08-23
    相关资源
    最近更新 更多