在 Alpine Linux 下编辑/隐藏 Nginx 服务器 header

Edit / hide Nginx Server header under Alpine Linux

当我使用 curl --head 测试我的网站时,它 returns 服务器信息。

我跟着this tutorial隐藏了nginx服务器header。 但是当我 运行 命令 yum install nginx-module-security-headers , 它 returns yum: not found.

我也试了apk add nginx-module-security-headers,结果显示包不见了

我使用 nginx:1.17.6-alpine 作为我的基础 docker 图片。有谁知道如何在这个 Alpine 下对 header 隐藏服务器?

Alpine repo 可能没有 ngx_security_headers 模块,但是,提到的教程还提供了使用 Headers More 模块的选项。您应该能够使用以下命令在您的 alpine 发行版中安装此模块:

apk add nginx-mod-http-headers-more

希望对您有所帮助。

Source

我找到了替代解决方案。之所以显示binary not compatible是因为我在target route下预装了一个nginx,和我用的header-more模块不兼容。这意味着我不能简单地从 Alpine 包中安装第三方库。

所以我准备了一个干净的 Alpine OS,并按照 GitHub repository 从源代码构建具有附加功能的 Nginx。构建结果的路径就是你指定的前缀路径。

我认为这里有一个更简单的解决方案:https://gist.github.com/hermanbanken/96f0ff298c162a522ddbba44cad31081。非常感谢 Github 上的 hermanbanken 分享了这个要点。

想法是使用 nginx alpine 映像创建一个多阶段构建,作为编译模块的基础。这变成以下 Dockerfile:

ARG VERSION=alpine
FROM nginx:${VERSION} as builder

ENV MORE_HEADERS_VERSION=0.33
ENV MORE_HEADERS_GITREPO=openresty/headers-more-nginx-module

# Download sources
RUN wget "http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz" -O nginx.tar.gz && \
    wget "https://github.com/${MORE_HEADERS_GITREPO}/archive/v${MORE_HEADERS_VERSION}.tar.gz" -O extra_module.tar.gz

# For latest build deps, see https://github.com/nginxinc/docker-nginx/blob/master/mainline/alpine/Dockerfile
RUN  apk add --no-cache --virtual .build-deps \
    gcc \
    libc-dev \
    make \
    openssl-dev \
    pcre-dev \
    zlib-dev \
    linux-headers \
    libxslt-dev \
    gd-dev \
    geoip-dev \
    perl-dev \
    libedit-dev \
    mercurial \
    bash \
    alpine-sdk \
    findutils

SHELL ["/bin/ash", "-eo", "pipefail", "-c"]

RUN rm -rf /usr/src/nginx /usr/src/extra_module && mkdir -p /usr/src/nginx /usr/src/extra_module && \
    tar -zxC /usr/src/nginx -f nginx.tar.gz && \
    tar -xzC /usr/src/extra_module -f extra_module.tar.gz

WORKDIR /usr/src/nginx/nginx-${NGINX_VERSION}

# Reuse same cli arguments as the nginx:alpine image used to build
RUN CONFARGS=$(nginx -V 2>&1 | sed -n -e 's/^.*arguments: //p') && \
    sh -c "./configure --with-compat $CONFARGS --add-dynamic-module=/usr/src/extra_module/*" && make modules


# Production container starts here
FROM nginx:${VERSION}

COPY --from=builder /usr/src/nginx/nginx-${NGINX_VERSION}/objs/*_module.so /etc/nginx/modules/

.... skipped inserting config files and stuff ...

# Validate the config
RUN nginx -t