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
    • 最新
    • 标签
主页 / user-1042206

Predaytor's questions

Martin Hope
Predaytor
Asked: 2023-10-19 21:33:31 +0800 CST

漆。如何使用 cookie 根据区域设置进行重定向?

  • 5

我需要为多语言站点实现基于 cookie 的重定向逻辑。我有 Next.js 中间件的工作代码,但不幸的是它无法在 Docker 的独立设置中工作(我不使用 Vercel)。

import { NextRequest, NextResponse } from 'next/server';

export const config = {
    matcher: [
        /*
         * Match all request paths except for the ones starting with:
         * - api (API routes)
         * - _next (static files)
         * - URLs ending with a file extension (e.g., .html, .js, .css, etc.)
         */
        '/((?!api|_next|\\.\\.).+)',
    ],
};

export function middleware(request: NextRequest) {
    const { pathname, search, defaultLocale, locale } = request.nextUrl;

    const localeCookie = request.cookies.get('NEXT_LOCALE')?.value;

    if (!localeCookie && locale !== defaultLocale) {
        return NextResponse.redirect(new URL(`/${defaultLocale}${pathname}${search}`, request.url));
    }

    if (localeCookie && locale !== localeCookie) {
        return NextResponse.redirect(new URL(`/${localeCookie}${pathname}${search}`, request.url));
    }

    return NextResponse.next();
}

我想实现 Varnish 设置而不是 Next.js 解决方案:

vcl 4.1;

import cookie;

sub vcl_recv {
    ...

    if (req.url ~ "^/_next" || req.url ~ "/api/" || req.url ~ "/\.(.*)$/") {
        return (pass);
    }

    # Extract the locale from the URL, the default locale is hidden
    if (req.url ~ "^/[a-z]{2}/") {
        set req.http.locale = regsub(req.url, "^/([a-z]{2})(/.*)?$", "\1");
    } else {
        set req.http.locale = "";
    }

    # Extract NEXT_LOCALE cookie
    if (req.http.cookie) {
        cookie.parse(req.http.cookie);
        set req.http.localeCookie = cookie.get("NEXT_LOCALE");
        set req.http.cookie = cookie.get_string();
    }

    // If locale is specified and NEXT_LOCALE is missing, redirect to the default locale.
    if (req.http.locale != "" && !req.http.localeCookie) {
        # set req.http.X-Redirect-Url = ...;
        return (synth(302));
    }
    // If NEXT_LOCALE is present and the locale is not equal to the locale from cookie, then redirect to the cookie locale
    else if (req.http.locale != "" && req.http.locale != req.http.localeCookie) {
        # set req.http.X-Redirect-Url = ...;
        return (synth(302));
    }

    ...

    return (hash);
}

sub vcl_synth {
    # Perform the actual redirection based on the X-Redirect-Url header
    if (resp.status == 302 && req.http.X-Redirect-Url) {
        set resp.http.location = req.http.X-Redirect-Url;
        set resp.reason = "Moved";
        return (deliver);
    }
}
varnish
  • 2 个回答
  • 128 Views
Martin Hope
Predaytor
Asked: 2023-08-10 02:39:33 +0800 CST

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

  • 5

我的 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 个回答
  • 50 Views

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