“重写目标"路由到Nginx服务器上的React.js应用程序时失败

问题描述:

我有一个React应用,我可以对其进行构建和dockerize托管在Nginx服务器上.

I have a React app which I build and dockerize to be hosted on a nginx server.

FROM nginx:latest
COPY build /usr/share/nginx/html

然后我为其创建一个简单的部署和服务(我非常怀疑这是问题所在).接下来,我创建一个nginx入口.

I then create a simple deployment and service for it (which I very much doubt are the problem). Next I create an nginx ingress.

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: my-app-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: <MY_NGINX_CONTROLLER_EXTERNAL_IP>.xip.io
    http:
      paths:
      - backend:
          serviceName: my-app-service
          servicePort: 80
        path: /myapp   

但是当我拨打<MY_NGINX_CONTROLLER_EXTERNAL_IP>.xip.io/myapp时,我得到了404.

But when I call <MY_NGINX_CONTROLLER_EXTERNAL_IP>.xip.io/myapp I get a 404.

当我将path: /myapp更改为path: /时,在<MY_NGINX_CONTROLLER_EXTERNAL_IP>.xip.io上可以正常访问我的应用程序

When I change path: /myapp to path: / I can reach my app with no problems on <MY_NGINX_CONTROLLER_EXTERNAL_IP>.xip.io

我已经尝试了rewrite-targetpath的许多变体,例如/$1/myapp/(.*),但这没什么区别.

I have tried numerous variations of rewrite-target and path like /$1 and /myapp/(.*) but it makes no difference.

我相信问题在于使用nginx.ingress.kubernetes.io/rewrite-target批注路由到React应用.因为将注释用于群集上的任何其他服务都很好.

I believe the problem lies with using the nginx.ingress.kubernetes.io/rewrite-target annotation to route to a React app. Because using that annotation for any other service on my cluster works just fine.

其他用户似乎也有类似的问题: https://github.com/kubernetes/ingress-nginx/issues/3770#.但是我找不到解决办法.

Others users seem to have similar problems: https://github.com/kubernetes/ingress-nginx/issues/3770#. But I was unable to find a solution.

一种解决方法是在我的应用程序中更改basenamehomepage属性,然后更新所有路由.这样我就完全不需要rewrite-target了.但是,使其与rewrite-target一起使用会更加整洁,尤其是考虑到必须为我的应用定期更改路径/子目录.

A workaround would be to change the basename and homepage attributes within my react app and then update all routes. Then I would not need rewrite-target at all. But making it work with rewrite-target would be much cleaner, especially considering that the path/subdirectory will have to change regularly for my app.

我现在可以正常使用了.通过两个额外的步骤,重写目标"可被称为重写目标".注释根本不是必需的,可以从入口资源中删除.

I got it working now. With two additional steps "rewrite-target" annotation is not required at all and can be removed from the ingress resource.

第1步:在react应用中更改基本URL.了解如何执行此操作

Step 1: Change the base URL within the react app. See how to do this here.

步骤2:将react build复制到Dockerfile中/usr/share/nginx/html的相应子目录中:

Step 2: Copy the react build into the corresponding subdirectory of /usr/share/nginx/html in the Dockerfile:

FROM nginx:latest
COPY build /usr/share/nginx/html/myapp