Nginx 重写代理传递(用于节点反应应用程序)

Nginx 重写代理传递(用于节点反应应用程序)

我在 localhost:3000 上运行 Node React 应用,使用 Nginx 进行反向代理并在 localhost/web/ 上公开。但是,应用生成的文件存在问题,因为它们未正确引用。

例如,一些 .js 文件在 localhost:3000/static/js 中生成,但链接未正确引用相对路径(见下面的代码)。我认为可以通过重写来修复此问题,但我现在使用的方式无法正常工作。我应该如何重写才能使所有相对链接都以 /web/ 开头?

生成的 html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="/favicon.ico" />
    <meta
    name="viewport"
    content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />
    <!--
    manifest.json provides metadata used when your web app is installed on a
    user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="/manifest.json" />
    <!--
    Template...
    ...
    -->
    <title>React App</title>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
    Template
    ...
    -->
<script src="/static/js/bundle.js"></script><script src="/static/js/0.chunk.js"></script><script src="/static/js/main.chunk.js"></script></body>
</html>

以下是我的 Nginx 站点可用代码片段:

server {
    listen 80;
    server_name localhost;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    include snippets/self-signed.conf;
    include snippets/ssl-params.conf;

    access_log /var/log/nginx/site.access.log;
    error_log /var/log/nginx/site.error.log error;

    add_header "Access-Control-Allow-Credentials" "true";
    add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS";
    add_header "X-Frame-Options" "SAMEORIGIN";

    location /web/ {
        proxy_set_header        Host            $http_host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        Upgrade         $http_upgrade;
        proxy_set_header        Connection      'upgrade';
        rewrite                 ^(.*)$ /web/$1 break;
        proxy_pass              http://localhost:3000/;
    }
}

相关内容