Nginx重写代理服务器通行证(用于节点响应应用)

时间:2019-05-03 14:21:52

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

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

例如,某些.js文件是在localhost:3000 / static / 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网站可用的代码段:

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

1 个答案:

答案 0 :(得分:0)

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

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