【问题标题】:Erlang Cowboy how to add response headers for static filesErlang Cowboy如何为静态文件添加响应头
【发布时间】:2021-03-26 01:37:47
【问题描述】:

我想将 Strict-Transport-Security 标头添加到 Web 应用程序中。

这里是设置

Dispatch = cowboy_router:compile([
    {'_', [
        {"/", cowboy_static, {file, env_file:filepath({data, "assets/index.html"})}}
    ]}
]),
{ok, _} = cowboy:start_tls(product_https,
    [
        {port, 8443},
        {certfile, env_file:filepath({etc, "ssl/cert.crt"})},
        {keyfile, env_file:filepath({etc, "ssl/key.key"})}
    ],
    #{env => #{dispatch => Dispatch}}
)

在提供静态文件时,我应该在哪里添加 HSTS 或其他自定义标头?

【问题讨论】:

    标签: http-headers erlang hsts cowboy


    【解决方案1】:

    使用中间件是解决办法。

    设置将是:

    Dispatch = cowboy_router:compile([
        {'_', [
            {"/", cowboy_static, {file, env_file:filepath({data, "assets/index.html"})}}
        ]}
    ]),
    {ok, _} = cowboy:start_tls(product_https,
        [
            {port, 8443},
            {certfile, env_file:filepath({etc, "ssl/cert.crt"})},
            {keyfile, env_file:filepath({etc, "ssl/key.key"})}
        ],
        #{
            env => #{dispatch => Dispatch},
            middlewares => [cowboy_router, my_security_middleware, cowboy_handler]}
        }
    )
    

    这是中间件的实现

    -module(my_security_middleware).
    -behaviour(cowboy_middleware).
    
    -export([execute/2]).
    
    execute(Req, Env) ->
        Req2 = cowboy_req:set_resp_header(<<"aaaaa">>, <<"bbbbb">>, Req),
        {ok, Req2, Env}.
    

    这会将标头 aaaaa: bbbbb 添加到所有请求响应中。

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 2017-05-31
      • 2012-10-10
      • 2019-02-02
      • 2011-08-30
      • 1970-01-01
      • 2017-01-14
      • 2021-01-05
      • 2015-12-06
      相关资源
      最近更新 更多