Nginx 反向代理到 nextjs 和 react-admin

Nginx reverse proxy to both nextjs and react-admin

我有一个用 nextjs 编写的现有应用程序,因为我需要 SSR。由于我在管理端不需要 SSR,所以我想使用 react-admin。我无意将两者集成,而是让它们 运行 作为单独的 processes/services 在不同的端口上,并让 nginx 执行代理路由。我在配置 react-admin 时遇到困难。

nginx 反向代理位置的配置:

server {
    server_name www.mydomainname.com;

    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;


    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
        proxy_redirect off;
     }

    location /admin {
        proxy_pass http://127.0.0.1:3001;
        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;
        proxy_redirect off;
     }

     # 301 Redirect URLs with trailing /'s
     #as per https://webmasters.googleblog.com/2010/04/to-slash-or-not-to-slash.html
     rewrite ^/(.*)/$ / permanent;


     # 301 redirect from custom redirect file
     if ( $redirect_uri ) {
        return 301 $redirect_uri;
     }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/mydomiainname.com/fullchain.pem # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/mydomainname.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

我相信 nginx 配置是正确的。当导航到 /admin 时,react-admin 响应一个空白 "React App" 页面,而不是从它的根路径“/”看到的默认页面。

我试过在 react-app package.json 文件中设置 'homepage': "/admin" 但没有成功。

我如何配置 react-app 以默认为 /admin 而不是 / 提供页面?

问题很可能是 react-admin 的代理路径是 /admin 而不是 /。为避免这种情况,您需要在 proxy_pass URL:

的末尾添加斜杠 /
location /admin {
    proxy_pass http://127.0.0.1:3001/;
    ...
}

这在 Nginx 文档的 proxy_pass 部分进行了解释,尽管不可否认该语言有点深奥:

If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive:

location /name/ {
    proxy_pass http://127.0.0.1/remote/;
}

If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:

location /some/path/ {
    proxy_pass http://127.0.0.1;
}