移除NGINX 301 返回的HTML body

起因

最近检查nginx的301转移,发现携带了Nginx默认的HTML body。

HTTP/1.1 301 Moved Permanently
Date: Wed, 12 Oct 2022 03:26:26 GMT
Content-Length: 0
Connection: keep-alive

<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.22.0</center>
</body>
</html>

其中包括了nginx信息,这是很不安全的。

解决

于是查了查资料, 可以这样解决:

例子1

server {
    listen 80

    error_page 301 302 @30x; 
    location @30x {
        default_type ""; # removes the Content-Type 
        return 300; # is needed but will never be used
    }

    location = /local {
        access_log off;
        proxy_pass http://localhost:8888/local;
    }

    if ($uri !~* /local) {
        return 301 https://$host$request_uri;
    }
}

1. 访问/local,会直接pass到本地8888端口

2.访问非/local,将301调转到https 443端口

例子2:

server {
    listen 1976;
    error_page 301 302 @30x; # keep original HTTP status code w/o `=`
    location @30x {
        default_type ""; # will remove Content-Type completely
        # `300` is a filler: client will get the original HTTP status code
        return 300;
    }
    return 301 http://example.su/test;
}

参考:

经验分享 程序员 微信小程序 职场和发展