LoginSignup
0
1

More than 1 year has passed since last update.

FastHttpd で nginx を代替してみる

Posted at

valyala/fasthttp を使って fasthttpd という http サーバを作ってみました。

大きなサービスでは ALB や Google Load Balancer 使うのですが、小さなサービスではまだまだ http サーバ使ってます。近頃の情勢でなんとなく nginx に代わるサービスないかなーと探していたところ valyala/fasthttp に出会い、開発に着手しました。

早速ですが、以下は私がよく使う nginx の設定ファイルです。 バックエンドは node や php で静的ファイルは nginx で配信します。

upstream backend {
    server 127.0.0.1:8000;
}

server {
    listen 80 default_server;
    return 302 https://$host$request_uri;
}

server {
    listen 443 default_server;
    ssl on;
    ssl_protocols      TLSv1 TLSv1.1 TLSv1.2;
    ssl_certificate  /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location ~ ^/(404|50.).html {
        root /usr/share/nginx/html;
        internal;
    }
    location ~ ^/(.*)\.(ico|css|git|jpg|jpeg|png|js)$ {
        alias /app/public/$1.$2;
    }
    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;
        proxy_intercept_errors on;
        proxy_pass http://backend;
    }
}

これを fasthttpd の設定ファイルにすると大体こんな感じになります。https の設定は超簡単です。

host: example.com
listen: ':80'

routes:
  - path: ^/(.*)$
    match: regexp
    rewrite: https://example.com/$1
    status: 302
---
host: example.com
listen: ':443'
root: /usr/share/fasthttpd/html
ssl:
  autoCert: true

errorPages:
  '404': /err/404.html
  '5xx': /err/5xx.html

handlers:
  'backend':
    type: proxy
    url: http://localhost:8080/
  'public':
    type: fs
    root: /app/public
    indexNames: [index.html]

routes:
  - path: ^/(.*)\.(ico|css|git|jpg|jpeg|png|js)$
    match: regexp
    handler: public
  - path: /
    handler: backend

特徴の 1つとして設定ファイルが yaml 形式なので jarxorg/tree を使って一部を上書きできます。

fasthttpd -f config.yaml -e handlers.public.root=path/to/other-root

設定ファイルの全容は https://fasthttpd.org/configuration にあります。
今後はぼちぼちと http/2, http/3 対応やロードバランシングの高速化などやっていく予定です。
フィードバックなどいただけたら励みになります!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1