nginx常用配置
配置多个域名
server {
listen 80;
server_name aaa.cn bbb.cn;
}
配置多个站点
server {
listen 80;
server_name aaa.cn;
location / {
root /home/project/pa;
index index.html;
}
}
server {
listen 80;
server_name bbb.cn ccc.cn;
location / {
root /home/project/pb;
index index.html;
}
}
静态资源缓存
请根据您的实际情况进行筛选
location ~ .*\.(?:js|css|jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm)$ {
expires 7d;
}
location ~ .*\.(?:htm|html)$ {
add_header Cache-Control "private, no-store, no-cache, must-revalidate, proxy-revalidate";
}
!注意:no-cache与no-store的区别,no-cache表示不缓存过期资源,缓存会向服务器进行有效处理确认之后处理资源,而no-store才是真正的不进行缓存。
正向代理
代理端代理的是客户端——请求目标明确
反向代理
代理端代理的是服务端——请求目标待分配
负载均衡
均衡分发请求,解决网络拥塞问题,提高服务器响应速度,
服务就近提供,达到更好的访问质量,减少后台服务器大并发压力
nginx负载均衡的算法
a1为服务器组,包含3台服务器(10.10.10.1、10.10.10.2、10.10.10.3)
server {
listen 80;
location / {
proxy_pass http://a1;
}
}
1、轮询循环(round-robin):循环均匀分配请求
upstream a1 {
server 10.10.10.1;
server 10.10.10.2;
server 10.10.10.3;
}
2、最少连接(least-connected):当前请求连接数最少
upstream a1 {
least_conn;
server 10.10.10.1;
server 10.10.10.2;
server 10.10.10.3;
}
3、IP哈希(ip-hash):由客户端IP地址确定
upstream a1 {
ip_hash;
server 10.10.10.1;
server 10.10.10.2;
server 10.10.10.3;
}
4、权重(weighted):按权重大的多处理
upstream a1 {
server 10.10.10.1 weight=3;
server 10.10.10.2;
server 10.10.10.3;
}
不允许通过IP访问
拒绝访问
server {
listen 80 default;
server_name _;
return 404;
}
重定向
server {
rewrite ^/(.*)$ https://baidu.com/$1 permanent;
}
404自动跳转到首页
server {
location / {
error_page 404 = @ops-coffee;
}
location @ops-coffee {
rewrite .* / permanent;
}
}
添加黑白名单
白名单:只允许192.168.1.0/24 网段主机访问
location /admin/ {
allow 192.168.1.0/24;
deny all;
}
黑名单:禁止192.168.1.0/24 网段主机访问
location /ops-coffee/ {
deny 192.168.1.0/24;
allow all;
}
限制请求方法
if ($request_method !~ ^(GET|POST)$ ) {return 405;}
$request_method能够获取到请求nginx的method
配置只允许GET\POST方法访问,其他的method返回405
拒绝User-Agent
if ($http_user_agent ~* LWP::Simple|BBBike|wget|curl) {return 444;}
有些不法者会利用wget/curl等工具扫描网站,通过禁止相应的user-agent来简单的防范
Nginx的444状态比较特殊,如果返回444那么客户端将不会收到服务端返回的信息,就像是网站无法连接一样
图片防盗链
valid_referers: 验证referer,其中none允许referer为空,blocked允许不带协议的请求,除了以上两类外仅允许referer为www.baidu.com或baidu.com时访问images下的图片资源,否则返回403
location /images/ {
valid_referers none blocked www.baidu.com baidu.com;
if ($invalid_referer) {
return 403;
}
}
给不符referer规则的请求重定向到一个默认图片,
location /images/ {
valid_referers blocked www.baidu.com baidu.com;
if ($invalid_referer) {
rewrite ^/images/.*\.(gif|jpg|jpeg|png)$ /static/qrcode.jpg last;
}
}
隐藏版本号
http {
server_tokens off;
}

浙公网安备 33010602011771号