Nginx的一些安全配置

不显示Nginx版本

在网站配置里面,server_name下面新增一行

server_tokens off;

不显示PHP版本

PHP的配置文件php.ini文件里找到配置项,expose_php,改为Off 

expose_php = Off

控制缓冲区溢出攻击

执行如下命令,编辑nginx.conf,为所有客户端设置缓冲区的大小限制。

vi /usr/local/nginx/conf/nginx.conf

编辑和设置所有客户端缓冲区的大小限制如下:

client_body_buffer_size  1K;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;

控制超时来提高服务器性能并与客户端断开连接

client_body_timeout   10;
client_header_timeout 10;
keepalive_timeout     5 5;
send_timeout          10;

限制可用的请求方法

只允许GET,HEAD和POST方法

if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 444;
}

如何拒绝一些User-Agents

阻止User-Agents,如扫描器,机器人以及滥用你服务器的垃圾邮件发送者

if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
    return 403;
}

图片防盗链

location /images/ {
    valid_referers none blocked www.example.com example.com;
    if ($invalid_referer) {
        return   403;
    }
}

重定向并显示指定图片

valid_referers blocked www.example.com example.com;
if ($invalid_referer) {
    rewrite ^/images/uploads.*.(gif|jpg|jpeg|png)$ http://www.examples.com/banned.jpg last
}

IP限制

location /docs/ {
    ## 禁止访问的IP
    deny    192.168.1.1;
    ## 允许访问的IP段 192.168.1.0/24
    allow   192.168.1.0/24;
    ## 拒绝其他IP访问
    deny    all;
}
Last modification:October 31, 2022
If you think my article is useful to you, please feel free to appreciate