一、限制访问Nginx的方式
1、使用密钥登录,禁用密码登录
# 打开sshd_config文件
vim /etc/ssh/sshd_config
#找到下面这2行
#PasswordAuthentication yes
#PermitEmptyPasswords no
#修改为
PasswordAuthentication no
PermitEmptyPasswords no
# 重启ssh服务
service sshd restart
2、限制Nginx服务器的访问来源
# 打开nginx.conf配置文件
vim /etc/nginx/nginx.conf
# 在http模块下加入下面语句,限定访问来源
http {
# ..
allow 127.0.0.1;
allow 192.168.0.0/16;
deny all;
# ..
}
# 重载Nginx配置
nginx -s reload
3、配置SSL/TLS协议,以加密和保护HTTP通信
# 安装SSL/TLS模块
yum install openssl nginx-mod-http-openssl
# 启用SSL/TLS,允许HTTPS连接
server {
listen 443 ssl;
server_name example.com;
ssl on;
ssl_certificate /path/to/cert.crt;
ssl_certificate_key /path/to/cert.key;
# ...
}
# 重载Nginx配置
nginx -s reload
二、使用Nginx内置模块加强Web应用防御机制
1、使用HttpLimitReqModule,用于限制请求速率
# 配置rate=5r/s,在5秒内允许最多发起5个请求
http {
#..
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=5r/s;
server {
#..
limit_req zone=mylimit burst=10 nodelay;
}
}
2、使用HttpLimitConnModule,用于限制客户端的并发连接数
# 配置客户端可同时保持的连接数
events {
worker_connections 1024;
}
# 给特定的IP地址配置限制连接数的功能
http {
#..
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
#..
limit_conn addr 2;
}
}
3、使用HttpAccessModule,用于限制访问IP、URL等
# 在http或server块中使用deny和allow指令
http {
#..
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
}
三、Nginx安全性的其他建议
1、定期更新安全补丁,以确保Nginx可以抵御新的漏洞攻击
# 执行命令更新系统软件包
yum update
2、关闭Nginx不需要的模块,以减少攻击面
# 打开nginx.conf
vim /etc/nginx/nginx.conf
# 取消注释下面这条,关闭不需要的模块
# include /etc/nginx/modules/*.conf;
# 重载Nginx配置
nginx -s reload
3、启用防火墙,以防止未授权的访问
# 安装firewalld,并启用服务
yum install firewalld
systemctl start firewalld
systemctl enable firewalld
# 禁止所有的入站网络流量,只允许指定的端口和来源IP,一路按照命令行提示操作
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --permanent --add-port=443/tcp
firewall-cmd --permanent --add-source=192.168.1.0/24
firewall-cmd --reload