nginx安全配置
vim nginx.conf
user nginx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
隐藏nginx版本号-curl -I
server_tokens off;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
限制IP地址的并发连接数
limit_conn_zone $binary_remote_addr zone=ops:10m;
types_hash_max_size 2048;
server {
listen 80;
server_name down-app.red-phoenix.com.cn;
rewrite ^(.*)$ https://$host$1 permanent;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
nginx HTTPS证书配置:
server {
listen 443 ssl;
ssl on; # 开启https
server_name down-app.red-phoenix.com.cn;
ssl_certificate /home/project/downApp/nginx/conf/cert/xxx.pem; # 配置nginx ssl证书的路径
ssl_certificate_key /home/project/downApp/nginx/conf/cert/xxx.key; #配置nginx ssl证书key的路径
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5; # 指定客户端连接时所使用的加密算法,你可以再这里配置更高安全的算法
ssl_prefer_server_ciphers on;
限制客户端请求的方法,配置只允许GET\POST方法访问,其他的method返回405
if ($request_method !~ ^(GET)$ ) {
return 405;
}
禁止利用wget/curl等工具扫描我们的网站;
if ($http_user_agent ~* LWP::Simple|BBBike|wget|curl) {
return 444;
}
匹配/opt/downApp/down目录的文件
location /down {
root /opt/downApp/;
autoindex on; #开启索引功能
autoindex_exact_size off; #关闭计算文件确切大小(单位bytes),只显示大概大小(单位kb、mb、gb)
autoindex_localtime on; #显示本机时间而非 GMT 时间
}
匹配默认nginx安装目录html下
location / {
root html;
index index.html index.htm;
限制IP地址的并发连接数,结合上面使用:limit_conn_zone
limit_conn ops 2;
}
添加黑白名单
location /admin/ {
allow 192.168.12.0/24;
deny all;
}
上边表示只允许192.168.12.0/24网段的主机访问,拒绝其他所有
也可以写成黑名单的方式禁止某些地址访问,允许其他所有,例如
location /ops-coffee/ {
deny 192.168.12.0/24;
allow all;
}
更多的时候客户端请求会经过层层代理,我们需要通过$http_x_forwarded_for来进行限制,可以这样写
set $allow false;
if ($http_x_forwarded_for = "211.23.56.2") { set $allow true; }
if ($http_x_forwarded_for ~ "132.7.66.8") { set $allow true; }
if ($allow = false) { return 404; }
添加账号认证
location / {
auth_basic "please input user&passwd";
auth_basic_user_file /opt/test/passtd/pass;
}
创建账号方法:
mkdir -p /opt/test/passtd
printf "ttlsa:$(openssl passwd -crypt 123456)\n" >> /opt/test/passtd/pass
cat /opt/test/passtd/pass
ttlsa:4wDzxPYMm4TGA
#说明:在登录nginx时,就需要输入账号和密码,输入文件中的账号和密码即可
}
}