リバースプロキシ

リバースプロキシは、クライアントからのリクエストを受け取り、それをバックエンドの1つまたは複数のサーバーに転送するサーバーアーキテクチャです。フォワードプロキシ(クライアントを代表する)とは異なり、リバースプロキシはサーバー側を代表して動作します。

リバースプロキシの主な利点:

  • 負荷分散:リクエストを複数のサーバーに分散
  • セキュリティ向上:実際のサーバー情報を隠蔽
  • コンテンツキャッシュ:パフォーマンス向上
  • パス書き換えと転送:柔軟なリクエストルーティング

Salvoフレームワークはリバースプロキシ機能を提供するミドルウェアを備えています。

サンプルコード

main.rs
Cargo.toml
use salvo::prelude::*;

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().init();

    // In this example, if the requested URL begins with <http://127.0.0.1:8698/>, the proxy goes to
    // <https://www.rust-lang.org>; if the requested URL begins with <http://localhost:8698/>, the proxy
    // goes to <https://crates.io>.
    let router = Router::new()
        .push(
            Router::new()
                .host("127.0.0.1")
                .path("{**rest}")
                .goal(Proxy::use_hyper_client("https://docs.rs")),
        )
        .push(
            Router::new()
                .host("localhost")
                .path("{**rest}")
                .goal(Proxy::use_hyper_client("https://crates.io")),
        );

    let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
    Server::new(acceptor).serve(router).await;
}