Nginx是一个轻量级,高性能的Web主机/反向代理和电子邮件 代理(IMAP/POP3),它可以运行在UNIX,GNU/Linux,BSD变种,MAC OS X,Solaris和Microsoft Windows上。根据Netcraft的调查数据显示,互联网上6%的域名都使用了Nginx Web主机。Nginx是解决C10K问题的主机之一,与传统主机不一样,Nginx不依赖于线程处理请求,相反,它使用了一个更具扩展性的事件驱 动(异步)架构。Nginx在很多高流量网站上得到了应用,如WordPress,Hulu,Github和SourceForge。
1、一些常识
1、顶部配置
#定义 Nginx 运行的用户和用户组 user nginx; #进程文件 pid /var/run/nginx.pid; #错误日志位置和级别,debug、info、notice、warn、error、crit error_log /var/log/nginx/error.log warn; #Nginx worker 的进程数,一般可设置为可用的CPU内核数。 worker_processes 8; #每个 worker 打开文件描述符的最大数量限制。理论值应该是最多打开文件数(系统的值ulimit -n)与 nginx 进程数相除,但是 nginx 分配请求并不均匀,所以建议与ulimit -n的值保持一致。 worker_rlimit_nofile 65535;
2、Events 模块
events { #设置一个worker进程同时打开的最大连接数 worker_connections 2048; #告诉nginx收到一个新连接通知后接受尽可能多的连接 multi_accept on; #设置用于复用客户端线程的轮询方法。如果你使用Linux 2.6+,你应该使用epoll。如果你使用*BSD,你应该使用kqueue。 use epoll; }
3、HTTP 模块
http { #隐藏 Nginx 的版本号,提高安全性。 server_tokens off; #开启高效文件传输模式,sendfile 指令指定 Nginx 是否调用sendfile 函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘 IO 重负载应用,可设置为 off,以平衡磁盘与网络 I/O 处理速度,降低系统的负载。 sendfile on; #是否开启目录列表访问,默认关闭。 autoindex off; #告诉 Nginx 在一个数据包里发送所有头文件,而不一个接一个的发送 tcp_nopush on; #告诉 Nginx 不要缓存数据,而是一段一段的发送--当需要及时发送数据时,就应该给应用设置这个属性,这样发送一小块数据信息时就不能立即得到返回值。Nginx 默认会始终工作在 tcp nopush 状态下。但是当开启前面的 sendfile on; 时,它的工作特点是 nopush 的最后一个包会自动转转换到 nopush off。为了减小那200ms的延迟,开启 nodelay on; 将其很快传送出去。结论就是 sendfile on; 开启时,tcp_nopush 和 tcp_nodelay 都是on 是可以的。 tcp_nodelay on; #日志格式设定 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_age
4、SERVER 模块
server { #监听端口,nginx 会根据请求的 HOST 来决定使用哪个 SERVER 段的配置。如果没有匹配的 server_name,则默认使用配置文件中第一个。加上 default_server 则可以以指定没有匹配时的默认规则。 #listen 80; listen 80 default_server; #域名可以有多个,用空格隔开 server_name www.test.com test.com; root /user/share/nginx/html/test; #404页面配置 error_page 404 /404.html; #配置 ssl,有需要时开启。 ssl on; ssl_certificate /etc/nginx/ssl/server.crt; ssl_certificate_key /etc/nginx/ssl/server.key; location / { index index.html index.php; } #图片缓存时间设置 location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ { expires 10d; } #JS和CSS缓存时间设置 location ~ .*.(js|css)?$ { expires 1h; } location ~ [^/]\.php(/|$) { fastcgi_index index.php; #开启 PATH_INFO 支持,作用就是把参数按照给定的正则表达式分割成 $fastcgi_script_name 和 $fastcgi_path_info。 #例如:请求 index.php/id/1 不加此行配置时,fastcgi_script_name 是 /index.php/id/1,fastcgi_path_info 是空。 #加上之后,fastcgi_script_name 是 index.php,fastcgi_path_info 是 /id/1 fastcgi_split_path_info ^(.+\.php)(.*)$; #此值即是 PHP 中 $_SERVER['SCRIPT_FILENAME'] 的值 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; #指定FastCGI主机监听端口与地址。须和 PHP-FPM 的设置相同。 #fastcgi_pass 127.0.0.1:9000; fastcgi_pass unix:/var/run/php5-fpm.sock; include fastcgi_params; } }
二、常见的方式
三、具体的配置
1、禁止php文件的访问及执行
location ~ /(attachments|upload)/.*\.(php|php5)?$ { deny all; }
2、禁止IP的访问
//禁止的写法 deny 10.0.0.0/24; //允许的写法 allow 10.0.0.0/24; deny all;
3、根据用户的真实 IP 做连接限制
## 这里取得原始用户的IP地址 map $http_x_forwarded_for $clientRealIp { "" $remote_addr; ~^(?P<firstAddr>[0-9\.]+),?.*$ $firstAddr; } ## 针对原始用户 IP 地址做限制 limit_conn_zone $clientRealIp zone=TotalConnLimitZone:20m ; limit_conn TotalConnLimitZone 50; limit_conn_log_level notice; ## 针对原始用户 IP 地址做限制 limit_req_zone $clientRealIp zone=ConnLimitZone:20m rate=10r/s; #limit_req zone=ConnLimitZone burst=10 nodelay; limit_req_log_level notice; ## 具体主机配置 server { listen 80; location ~ \.php$ { ## 最多 5 个排队, 由于每秒处理 10 个请求 + 5个排队,你一秒最多发送 15 个请求过来,再多就直接返回 503 错误给你了 limit_req zone=ConnLimitZone burst=5 nodelay; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } }
4、 经过多层CDN之后取得原始用户的IP地址,nginx 配置
map $http_x_forwarded_for $clientRealIp { ## 没有通过代理,直接用 remote_addr "" $remote_addr; ## 用正则匹配,从 x_forwarded_for 中取得用户的原始IP ## 例如 X-Forwarded-For: 202.123.123.11, 208.22.22.234, 192.168.2.100,... ## 这里第一个 202.123.123.11 是用户的真实 IP,后面其它都是经过的 CDN 主机 ~^(?P<firstAddr>[0-9\.]+),?.*$ $firstAddr; } ## 通过 map 指令,我们为 nginx 创建了一个变量 $clientRealIp ,这个就是 原始用户的真实 IP 地址, ## 不论用户是直接访问,还是通过一串 CDN 之后的访问,我们都能取得正确的原始IP地址
5、隐藏版本信息
server_tokens off; proxy_hide_header X-Powered-By; //或者编译的时候修改源代码
6、禁用非必要的方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; }
7、禁用扩展名
location ~* .(txt|doc|sql|gz|svn|git)$ { deny all; }
8、合理配置响应头
add_header Strict-Transport-Security "max-age=31536000"; add_header X-Frame-Options deny; add_header X-Content-Type-Options nosniff; add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://a.disquscdn.com; img-src 'self' data: https://www.google-analytics.com; style-src 'self' 'unsafe-inline'; frame-src https://disqus.com";
Strict-Transport-Security(简称为 HSTS)可以告诉浏览器,在指定的 max-age 内,始终通过 HTTPS 访问
X-Frame-Options 用来指定此网页是否允许被 iframe 嵌套,deny 就是不允许任何嵌套发生
9、拒绝一些User-Agents
if ($http_user_agent ~* LWP::Simple|BBBike|wget) { return 403; }
10、防止图片盗链
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 } 11、控制缓冲区溢出攻击 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;
解释说明
1、client_body_buffer_size 1k-(默认8k或16k)这个指令可以指定连接请求实体的缓冲区大小。如果连接请求超过缓存区指定的值,那么这些请求实体的整体或部分将尝试写入一个临时文件。
2、client_header_buffer_size 1k-指令指定客户端请求头部的缓冲区大小。绝大多数情况下一个请求头不会大于1k,不过如果有来自于wap客户端的较大的cookie它可能会大于1k,Nginx将分配给它一个更大的缓冲区,这个值可以在large_client_header_buffers里面设置。
3、client_max_body_size 1k-指令指定允许客户端连接的最大请求实体大小,它出现在请求头部的Content-Length字段。如果请求大于指定的值,客户端将收到一个”Request Entity Too Large” (413)错误。记住,浏览器并不知道怎样显示这个错误。
4、large_client_header_buffers-指定客户端一些比较大的请求头使用的缓冲区数量和大小。请求字段不能大于一个缓冲区大小,如果客户端发送一个比较大的头,nginx将返回”Request URI too large” (414)
1、client_body_timeout 10;-指令指定读取请求实体的超时时间。这里的超时是指一个请求实体没有进入读取步骤,如果连接超过这个时间而客户端没有任何响应,Nginx将返回一个”Request time out” (408)错误。
2、client_header_timeout 10;-指令指定读取客户端请求头标题的超时时间。这里的超时是指一个请求头没有进入读取步骤,如果连接超过这个时间而客户端没有任何响应,Nginx将返回一个”Request time out” (408)错误。
3、keepalive_timeout 5 5; – 参数的第一个值指定了客户端与主机长连接的超时时间,超过这个时间,主机将关闭连接。参数的第二个值(可选)指定了应答头中Keep-Alive: timeout=time的time值,这个值可以使一些浏览器知道什么时候关闭连接,以便主机不用重复关闭,如果不指定这个参数,nginx不会在应答头中发送Keep-Alive信息。(但这并不是指怎样将一个连接“Keep-Alive”)参数的这两个值可以不相同。
4、send_timeout 10; 指令指定了发送给客户端应答后的超时时间,Timeout是指没有进入完整established状态,只完成了两次握手,如果超过这个时间客户端没有任何响应,nginx将关闭连接。
12、控制并发连接
limit_zone slimits $binary_remote_addr 5m; limit_conn slimits 5;
13、sysctl.conf配置
# Avoid a smurf attack net.ipv4.icmp_echo_ignore_broadcasts = 1 # Turn on protection for bad icmp error messages net.ipv4.icmp_ignore_bogus_error_responses = 1 # Turn on syncookies for SYN flood attack protection net.ipv4.tcp_syncookies = 1 # Turn on and log spoofed, source routed, and redirect packets net.ipv4.conf.all.log_martians = 1 net.ipv4.conf.default.log_martians = 1 # No source routed packets here net.ipv4.conf.all.accept_source_route = 0 net.ipv4.conf.default.accept_source_route = 0 # Turn on reverse path filtering net.ipv4.conf.all.rp_filter = 1 net.ipv4.conf.default.rp_filter = 1 # Make sure no one can alter the routing tables net.ipv4.conf.all.accept_redirects = 0 net.ipv4.conf.default.accept_redirects = 0 net.ipv4.conf.all.secure_redirects = 0 net.ipv4.conf.default.secure_redirects = 0 # Don't act as a router net.ipv4.ip_forward = 0 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.default.send_redirects = 0 # Turn on execshild kernel.exec-shield = 1 kernel.randomize_va_space = 1 # Tuen IPv6 net.ipv6.conf.default.router_solicitations = 0 net.ipv6.conf.default.accept_ra_rtr_pref = 0 net.ipv6.conf.default.accept_ra_pinfo = 0 net.ipv6.conf.default.accept_ra_defrtr = 0 net.ipv6.conf.default.autoconf = 0 net.ipv6.conf.default.dad_transmits = 0 net.ipv6.conf.default.max_addresses = 1 # Optimization for port usefor LBs # Increase system file descriptor limit fs.file-max = 65535 # Allow for more PIDs (to reduce rollover problems); may break some programs 32768 kernel.pid_max = 65536 # Increase system IP port limits net.ipv4.ip_local_port_range = 2000 65000 # Increase TCP max buffer size setable using setsockopt() net.ipv4.tcp_rmem = 4096 87380 8388608 net.ipv4.tcp_wmem = 4096 87380 8388608 # Increase Linux auto tuning TCP buffer limits # min, default, and max number of bytes to use # set max to at least 4MB, or higher if you use very high BDP paths # Tcp Windows etc net.core.rmem_max = 8388608 net.core.wmem_max = 8388608 net.core.netdev_max_backlog = 5000 net.ipv4.tcp_window_scaling = 1
14、在防火墙级限制每个IP的连接数
/sbin/iptables -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set /sbin/iptables -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 15 -j DROP
15、限制Nginx连接传出
/sbin/iptables -A OUTPUT -o eth0 -m owner --uid-owner vivek -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。