AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / server / 问题 / 1141164
Accepted
Predaytor
Predaytor
Asked: 2023-08-10 02:39:33 +0800 CST2023-08-10 02:39:33 +0800 CST 2023-08-10 02:39:33 +0800 CST

如何为 Node.js 设置 Nginx 和 Varnish 反向代理?

  • 772

我的 Astro 框架(Node.js SSR 适配器)网站部署在阿姆斯特丹地区的1 个shared-cpu-1x@256MB Fly.io实例上,该实例自动处理 gzip、TSL 终止。

初始设置包括端口 80 上的 Varnish -> Nginx 8080 -> Node.js 3000。

Varnish 处理静态资源和动态请求的所有缓存,Nginx 主要用于重写/重定向 URL,在主应用程序之上提供错误页面。

经过一些研究,我发现 Nginx 更适合提供静态内容,因此 Varnish 将接收已经更改的(如果需要)URL 并且仅提供动态内容。另外,在之前的配置中,我在Vary为 Varnish 标记的静态资源重复标头时遇到了麻烦。这是代替之前设置的正确方法吗?

新设置:Nginx 端口 80 -> Varnish 8080 -> Node.js 3000。

如何正确配置静态资源var/www/html/client一年的缓存?这会干扰 Varnish 提供的动态路由吗?非常感谢。

nginx/nginx.conf

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log stdout;
    error_log stderr info;

    upstream varnish {
        server localhost:8080;
    }

    server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html/client;
        index index.html;

        server_tokens off;

        error_page 404 /404.html;

        location = /404.html {
            internal;
        }

        location = /robots.txt {
            log_not_found off; access_log off; allow all;
        }

        location ~* \.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$ {
            log_not_found off;
            add_header Cache-Control "public, max-age=31536000, immutable";
            add_header X-Static-File "true";
            expires max;
        }

        # Redirect URLs with a trailing slash to the URL without the slash
        location ~ ^(.+)/$ {
            return 301 $1$is_args$args;
        }

        # Redirect static pages to URLs without `.html` extension
        location ~ ^/(.*)(\.html|index)(\?|$) {
            return 301 /$1$is_args$args;
        }

        location / {
            try_files $uri $uri/index.html $uri.html @proxy;
        }

        location @proxy {
            proxy_http_version 1.1;
            proxy_cache_bypass $http_upgrade;

            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            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 X-Forwarded-Proto $scheme;

            proxy_redirect off;
            proxy_pass http://varnish;

            proxy_intercept_errors on;
        }
    }
}

varnish/default.vcl

vcl 4.1;

import std;

backend default {
    .host = "127.0.0.1";
    .port = "3000";
}

acl purge {
    "localhost";
    "127.0.0.1";
    "::1";
}

sub vcl_recv {
    // Remove empty query string parameters
    // e.g.: www.example.com/index.html?
    if (req.url ~ "\?$") {
        set req.url = regsub(req.url, "\?$", "");
    }

    // Remove port number from host header
    set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");

    // Sorts query string parameters alphabetically for cache normalization purposes
    set req.url = std.querysort(req.url);

    // Remove the proxy header to mitigate the httpoxy vulnerability
    // See https://httpoxy.org/
    unset req.http.proxy;

    // Only handle relevant HTTP request methods
    if (
        req.method != "GET" &&
        req.method != "HEAD" &&
        req.method != "PUT" &&
        req.method != "POST" &&
        req.method != "PATCH" &&
        req.method != "TRACE" &&
        req.method != "OPTIONS" &&
        req.method != "DELETE"
    ) {
        return (pipe);
    }

    // Only cache GET and HEAD requests
    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    // Purge logic to remove objects from the cache.
    if (req.method == "PURGE") {
        if (client.ip !~ purge) {
            return (synth(405, "Method Not Allowed"));
        }
        return (purge);
    }

    // Mark static files with the X-Static-File header, and remove any cookies
    // X-Static-File is also used in vcl_backend_response to identify static files
    if (req.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") {
        set req.http.X-Static-File = "true";
        unset req.http.Cookie;
        return (hash);
    }

    // No caching of special URLs, logged in users and some plugins
    if (
        req.http.Authorization ||
        req.url ~ "^/preview=" ||
        req.url ~ "^/\.well-known/acme-challenge/"
    ) {
        return (pass);
    }

    // Remove any cookies left
    unset req.http.Cookie;

    return (hash);
}

sub vcl_pipe {
    // If the client request includes an "Upgrade" header (e.g., for WebSocket or HTTP/2),
    // set the same "Upgrade" header in the backend request to preserve the upgrade request
    if (req.http.upgrade) {
        set bereq.http.upgrade = req.http.upgrade;
    }
    return (pipe);
}

sub vcl_backend_response {
    // Inject URL & Host header into the object for asynchronous banning purposes
    set beresp.http.x-url = bereq.url;
    set beresp.http.x-host = bereq.http.host;

    // Set the default grace period if backend is down
    set beresp.grace = 1d;

    // Stop cache insertion when a backend fetch returns an 5xx error
    if (beresp.status >= 500 && bereq.is_bgfetch) {
        return (abandon);
    }

    // Cache 404 response for short period
    if (beresp.status == 404) {
        set beresp.ttl = 60s;
    }

    // Create cache variations depending on the request protocol and encoding type
    if (beresp.http.Vary) {
        set beresp.http.Vary = beresp.http.Vary + ", X-Forwarded-Proto, Accept-Encoding";
    } else {
        set beresp.http.Vary = "X-Forwarded-Proto, Accept-Encoding";
    }

    // If the file is marked as static cache it for 1 year
    if (bereq.http.X-Static-File == "true" && beresp.http.Cache-Control == "public, max-age=0") {
        unset beresp.http.Set-Cookie;
        set beresp.http.X-Static-File = "true";
        set beresp.ttl = 1y;
    }
}

sub vcl_deliver {
    // Check if the object has been served from cache (HIT) or fetched from the backend (MISS)
    if (obj.hits > 0) {
        // For cached objects with a TTL of 0 seconds but still in grace mode, mark as STALE
        if (obj.ttl <= 0s && obj.grace > 0s) {
            set resp.http.X-Cache = "STALE";
        } else {
            // For regular cached objects, mark as HIT
            set resp.http.X-Cache = "HIT";
        }
    } else {
        // For uncached objects, mark as MISS
        set resp.http.X-Cache = "MISS";
    }

    // Set the X-Cache-Hits header to show the number of times the object has been served from cache
    set resp.http.X-Cache-Hits = obj.hits;

    // Unset certain response headers to hide internal information from the client
    unset resp.http.x-url;
    unset resp.http.x-host;
    unset resp.http.x-varnish;
    unset resp.http.via;
}
nginx
  • 1 1 个回答
  • 50 Views

1 个回答

  • Voted
  1. Best Answer
    Thijs Feryn
    2023-08-10T17:05:50+08:002023-08-10T17:05:50+08:00

    Nginx 是一个很棒的 Web 服务器,Varnish 是一个很棒的缓存,两者都是很棒的反向代理服务器。

    如果您仅使用 Nginx 进行 URL 重写、重定向和错误处理,那么您实际上并不需要 Nginx。清漆也能做到这一点。

    VCL模板

    我推荐的基本 VCL 配置如下: https: //www.varnish-software.com/developers/tutorials/example-vcl-template/

    它是 Varnish Software 推荐的非特定于框架的 VCL。它涵盖以下项目:

    • 从 URL 中删除营销活动参数
    • 对查询字符串进行排序
    • 标头清理
    • 静态文件缓存
    • 后端健康检查
    • 边缘侧包含解析
    • 设置X-Forwarded-Proto标题
    • 剥离跟踪cookie
    • 创建协议感知的缓存变体

    网址重写

    如果要执行 URL 重写,可以在 VCL 中编写 if 语句并通过 重置 URL set req.url = "..."。您还可以使用该函数执行查找/替换regsuball()并使用正则表达式。

    有关基本 VCL 教程,请参阅https://www.varnish-software.com/developers/tutorials/varnish-configuration-language-vcl 。

    以下是 Nginx 配置中 2 个重写规则的 VCL 解释:

    sub vcl_recv {
        if(req.url ~ "^(.+)/$") {
            return(synth(301,regsuball(req.url,"^(.+)/$","\1")));
        }
    
        if(req.url ~ "^/(.*)(\.html|index)(\?|$)") {
            return(synth(301,regsuball(req.url,"^/(.*)(\.html|index)(\?|$)","/\1")));
        }
    }
    
    sub vcl_synth {
        if(resp.status == 301) {
            set resp.http.Location = resp.reason;
            set resp.reason = "Moved Permanently";
            set resp.body = "Redirecting.";
            return(deliver);
        }
    }
    

    此示例代码将重定向/test/到/test和/test.html,/test就像您的 Nginx 配置中一样。

    错误处理

    来自后端的错误在VCL的vcl_backend_error子例程中处理并且可以定制。

    您还可以根据传入的请求在 Varnish 中生成自己的错误。return(synth(INT status, STRING reason);您可以通过返回VCL 代码来完成此操作。我们已经在 URL 重定向示例中做到了这一点。

    自定义合成响应的输出与后端错误类似,发生在vcl_synth子例程中。

    以下是如何修改后端和合成错误的输出模板的示例。该示例使用 HTML 模板:https://www.varnish-software.com/developers/tutorials/vcl-synthetic-output-template-file/

    这应该可以让您清楚地了解如何处理来自 NodeJS 应用程序的错误。

    是否保留 Nginx 在设置中?

    根据您描述的情况,您实际上并不需要 Nginx。所有缓存和反向代理逻辑都可以在 Varnish 中轻松完成。

    然而,有两个理由证明在这个项目中使用 Nginx 是合理的:

    • TLS 处理
    • 缓存大量静态数据

    我们先来说说TLS:开源版本的Varnish目前不支持原生TLS。虽然商业版本可以,但对于开源版本的 Varnish,则需要终止 TLS。

    我们开发了自己的 TLS 代理。它称为Hitch,与 Varnish 配合得非常好。有关教程,请参阅https://www.varnish-software.com/developers/tutorials/terminate-tls-varnish-hitch/ 。

    但有人可能会说,如果您已经决定使用 Nginx,那么您不妨在连接到 Varnish 之前使用它来终止 TLS 会话。

    另一个原因可能是静态数据。不要误会我的意思:Varnish 非常擅长缓存静态数据,甚至可能比 Nginx 更快。然而,在 Varnish 中缓存大量静态数据可能会占用你的缓存空间。

    在 Varnish 中,您需要指定用于缓存的内存量。如果您只分配了 1GB 内存并缓存了 2GB 静态文件,则您的缓存最终可能会完全满。这不是一个大问题,因为最近最少使用的算法会通过删除长尾内容来自动清理空间。但如果这不可接受,Nginx 仍然可以使用。

    如果你的静态文件集合是1GB,但是你的缓存更大,那么你真的不需要添加Nginx。

    • 0

相关问题

  • Gzip 与反向代理缓存

  • nginx 作为代理的行为

  • Nginx 学习资源 [关闭]

  • 提供 70,000 个静态文件 (jpg) 的最佳方式?

  • 在 Apache、LightTPD 和 Nginx Web 服务器上提供 PHP 5.x 应用程序的现状?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    新安装后 postgres 的默认超级用户用户名/密码是什么?

    • 5 个回答
  • Marko Smith

    SFTP 使用什么端口?

    • 6 个回答
  • Marko Smith

    命令行列出 Windows Active Directory 组中的用户?

    • 9 个回答
  • Marko Smith

    什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同?

    • 3 个回答
  • Marko Smith

    如何确定bash变量是否为空?

    • 15 个回答
  • Martin Hope
    Tom Feiner 如何按大小对 du -h 输出进行排序 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich 什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent 如何确定bash变量是否为空? 2009-05-13 09:54:48 +0800 CST
  • Martin Hope
    cletus 您如何找到在 Windows 中打开文件的进程? 2009-05-01 16:47:16 +0800 CST

热门标签

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve