【问题标题】:Nginx rewrite proxy pass (For node react app)Nginx 重写代理通行证(对于节点反应应用程序)
【发布时间】:2019-09-22 02:46:34
【问题描述】:

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

例如,在 localhost:3000/static/js 中生成了一些 .js 文件,但链接未正确引用相对路径(请参阅下面生成的 html 代码)。我认为可以通过重写来解决这个问题,但是我现在拥有的方式无法正常工作。甚至可以通过重写来解决这个问题,我应该如何重写,以便所有相关链接都以 /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 站点-可用sn-p:

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/;
    }
}

【问题讨论】:

    标签: reactjs nginx reverse-proxy nginx-reverse-proxy


    【解决方案1】:

    您的rewrite 指令似乎错误。您的 NodeJS 应用程序中不存在您的 /web 路径。尝试编辑:

        rewrite                 ^/web/(.*)$ /$1 break;
    

    【讨论】:

    • 谢谢,但它会导致生成的 html 具有无效的相对路径
    猜你喜欢
    • 2021-02-04
    • 2020-02-16
    • 2019-10-21
    • 1970-01-01
    • 2019-09-19
    • 2019-08-17
    • 2020-03-13
    • 2018-06-25
    • 2021-05-22
    相关资源
    最近更新 更多