[svc]nginx常用功能配置
来源:互联网 发布:龙之信条优化设置 编辑:程序博客网 时间:2024/06/06 16:41
## k8s node节点的nginx配置
用于多apiserver时候, node节点的nginx访问3台apiserver时候的配置. nignx是pod跑的,网络是-net模式
error_log stderr notice;worker_processes auto;events { multi_accept on; use epoll; worker_connections 1024;}stream { upstream kube_apiserver { least_conn; server 192.168.8.161:6443; server 192.168.8.162:6443; server 192.168.8.163:6443; } server { listen 127.0.0.1:6443; proxy_pass kube_apiserver; proxy_timeout 10m; proxy_connect_timeout 1s; }}
nginx编译安装:
1,安装依赖
yum install pcre pcre-devel openssl openssl-devel –y
2,
useradd -s /sbin/nologin -M nginx
3,编译安装
./configure --user=nginx --group=nginx --prefix=/application/nginx-1.6.2 --with-http_stub_status_module --with-http_ssl_modulemake && make installecho $?ln -s /application/nginx-1.6.2/ /application/nginx
3,检查
/application/nginx/sbin/nginx -t 检查语法/application/nginx/sbin/nginx #启动
4,优化
echo PATH=/application/nginx/sbin/:$PATH >> /etc/profilesource /etc/profilenetstat -ntulp |grep nginxlsof -i:80 curl 192.168.14.151nginx -s stopnginx -s reload
nginx配置
- web服务器
- 反向代理
- 缓存,类似squid
nginx配置
worker_processes 2;error_log logs/error.log error;events { worker_connections 1024;}http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; include extra/www.conf; include extra/bbs.conf; include extra/blog.conf;}
server { listen 80; server_name www.shizi.ml; root /data/html/www; index index.html index.php index.htm; access_log logs/www_access.log;}
server { listen 80; server_name bbs.shizi.ml; root /data/html/bbs; index index.html index.php index.htm; access_log logs/bbs_access.log;}
nginx日志切割-logrotate
cat > /etc/logrotate.d/nginx /usr/local/nginx/logs/*.log { daily missingok rotate 7 dateext compress delaycompress notifempty sharedscripts postrotate if [ -f /usr/local/nginx/logs/nginx.pid ]; then kill -USR1 `cat /usr/local/nginx/logs/nginx.pid` fi endscript }
nginx日志json格式
log_format json '{"@timestamp": "$time_iso8601",' '"@version": "1",' '"client": "$remote_addr",' '"url": "$uri", ' '"status": $status, ' '"domain": "$host", ' '"host": "$server_addr",' '"size":"$body_bytes_sent", ' '"response_time": $request_time, ' '"referer": "$http_referer", ' '"http_x_forwarded_for": "$http_x_forwarded_for", ' '"ua": "$http_user_agent" } ';#access_log /var/log/nginx/lb_nginx-log-node11-52/node11-lb_nginx-access.log json;
nginx header参数
$arg_PARAMETER: 这个变量包含GET请求中,如果有变量PARAMETER时的值。$args: 这个变量等于请求行中(GET请求)的参数,例如foo=123&bar=blahblah;$binary_remote_addr: 二进制的客户地址。$body_bytes_sent: 响应时送出的body字节数数量。即使连接中断,这个数据也是精确的。$content_length: 请求头中的Content-length字段。$content_type: 请求头中的Content-Type字段。$cookie_COOKIE: cookie COOKIE变量的值$document_root: 当前请求在root指令中指定的值。$document_uri: 与$uri相同。$host: 请求主机头字段,否则为服务器名称。$hostname: #Set to the machine’s hostname as returned by gethostname$http_HEADER:$is_args: 如果有$args参数,这个变量等于”?”,否则等于””,空值。$http_user_agent: 客户端agent信息$http_cookie: 客户端cookie信息$limit_rate: 这个变量可以限制连接速率。$query_string: 与$args相同。$request_body_file: 客户端请求主体信息的临时文件名。$request_method: 客户端请求的动作,通常为GET或POST。$remote_addr: 客户端的IP地址。$remote_port: 客户端的端口。$remote_user: 已经经过Auth Basic Module验证的用户名。$request_completion: 如果请求结束,设置为OK. 当请求未结束或如果该请求不是请求链串的最后一个时,为空(Empty)。$request_method: GET或POST$request_filename: 当前请求的文件路径,由root或alias指令与URI请求生成。$request_uri: 包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”,不能修改。$scheme: HTTP方法(如http,https)。$server_protocol: 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。$server_addr: 服务器地址,在完成一次系统调用后可以确定这个值。$server_name: 服务器名称。$server_port: 请求到达服务器的端口号。$uri: 不带请求参数的当前URI,$uri不包含主机名,如”/foo/bar.html”。该值有可能和$request_uri不一致。$request_uri是浏览器发过来的值,该值是rewrite后的值。例如做了internal redirects后。
nginx日志切割-脚本
#!/bin/bash# This script run at 00:00LOG_PATH="/data/logs/nginx/"DATE=`date -d "yesterday" +%Y-%m-%d`mv ${LOG_PATH}/access.log ${LOG_PATH}/${DATE}.logsystemctl reload nginxfind $LOG_PATH -mtime +30 -exec rm -rf {} \;
nginx突破十万并发-配置
1,nginx配置-注释版:
worker_processes 8;#nginx进程数,建议按照cpu 数目来指定,一般为它的倍数 (如,2个四核的cpu计为8)。worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;#为每个进程分配cpu,上例中将8个进程分配到8个cpu,当然可以写多个,或者将一个进程分配到多个cpu。worker_rlimit_nofile 65535;#一个nginx进程打开的最多文件数目,理论值应该是最多打开文件数(ulimit -n)与nginx 进程数相除,但是nginx 分配请求并不是那么均匀,所以最好与ulimit -n 的值保持一致。假如设置10240,总并发量达到3-4万时就有进程可能超过10240了,这时会返回502错误。use epoll;#使用epoll的I/O模型#补充说明:# 与apache相类,nginx针对不同的操作系统,有不同的事件模型# - 标准事件模型# Select、poll属于标准事件模型,如果当前系统不存在更有效的方法,nginx会选择select或poll# - 高效事件模型# Kqueue:使用于 FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X. 使用双处理器的MacOS X系统使用kqueue可能会造成内核崩溃。# Epoll: 使用于Linux内核2.6版本及以后的系统。# /dev/poll:使用于 Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。# Eventport:使用于 Solaris 10. 为了防止出现内核崩溃的问题, 有必要安装安全补丁。worker_connections 65535;#每个进程允许的最多连接数, 理论上每台nginx 服务器的最大连接数为worker_processes*worker_connections。keepalive_timeout 60;#keepalive 超时时间。client_header_buffer_size 4k;#客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE 取得。#但也有client_header_buffer_size超过4k的情况,但是client_header_buffer_size该值必须设置为“系统分页大小”的整倍数。open_file_cache max=65535 inactive=60s;#这个将为打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive 是指经过多长时间文件没被请求后删除缓存。open_file_cache_valid 80s;#这个是指多长时间检查一次缓存的有效信息。open_file_cache_min_uses 1;#open_file_cache 指令中的inactive参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如果有一个文件在inactive时间内一次没被使用,它将被移除。
nginx配置-无注释版
worker_processes 8;worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;worker_rlimit_nofile 65535;use epoll;worker_connections 65535;keepalive_timeout 60;client_header_buffer_size 4k;open_file_cache max=65535 inactive=60s;open_file_cache_valid 80s;open_file_cache_min_uses 1;
2,关于内核参数的优化说明
net.ipv4.tcp_max_tw_buckets = 6000#timewait的数量,默认是180000。net.ipv4.ip_local_port_range = 1024 65000#允许系统打开的端口范围。net.ipv4.tcp_tw_recycle = 1#启用timewait快速回收。net.ipv4.tcp_tw_reuse = 1#开启重用。允许将TIME-WAIT sockets重新用于新的TCP 连接。net.ipv4.tcp_syncookies = 1#开启SYN Cookies,当出现SYN 等待队列溢出时,启用cookies 来处理。net.core.somaxconn = 262144#web 应用中listen 函数的backlog 默认会给我们内核参数的net.core.somaxconn 限制到128,而nginx 定义的NGX_LISTEN_BACKLOG 默认为511,所以有必要调整这个值。net.core.netdev_max_backlog = 262144#每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。net.ipv4.tcp_max_orphans = 262144#系统中最多有多少个TCP套接字不被关联到任何一个用户文件句柄上。如果超过这个数字,孤儿连接将即刻被复位并打印出警告信息。这个限制仅仅是为了防止简单的DoS 攻击,不能过分依靠它或者人为地减小这个值,更应该增加这个值(如果增加了内存之后)。net.ipv4.tcp_max_syn_backlog = 262144#记录的那些尚未收到客户端确认信息的连接请求的最大值。对于有128M 内存的系统而言,缺省值是1024,小内存的系统则是128。net.ipv4.tcp_timestamps = 0#时间戳可以避免序列号的卷绕。一个1Gbps 的链路肯定会遇到以前用过的序列号。时间戳能够让内核接受这种“异常”的数据包。这里需要将其关掉。net.ipv4.tcp_synack_retries = 1#为了打开对端的连接,内核需要发送一个SYN 并附带一个回应前面一个SYN 的ACK。也就是所谓三次握手中的第二次握手。这个设置决定了内核放弃连接之前发送SYN+ACK 包的数量。net.ipv4.tcp_syn_retries = 1#在内核放弃建立连接之前发送SYN 包的数量。net.ipv4.tcp_fin_timeout = 1#如果套接字由本端要求关闭,这个参数决定了它保持在FIN-WAIT-2状态的时间。对端可以出错并永远不关闭连接,甚至意外当机。缺省值是60秒。2.2内核的通常值是180秒,3你可以按这个设置,但要记住的是,即使你的机器是一个轻载的WEB服务器,也有因为大量的死套接字而内存溢出的风险,FIN- WAIT-2 的危险性比FIN-WAIT-1 要小,因为它最多只能吃掉1.5K 内存,但是它们的生存期长些。net.ipv4.tcp_keepalive_time = 30#当keepalive 起用的时候,TCP 发送keepalive 消息的频度。缺省是2 小时。
完整的内核优化设置
CentOS中可以将所有内容清空直接替换为如下内容:
net.ipv4.ip_forward = 0net.ipv4.conf.default.rp_filter = 1net.ipv4.conf.default.accept_source_route = 0kernel.sysrq = 0kernel.core_uses_pid = 1net.ipv4.tcp_syncookies = 1kernel.msgmnb = 65536kernel.msgmax = 65536kernel.shmmax = 68719476736kernel.shmall = 4294967296net.ipv4.tcp_max_tw_buckets = 6000net.ipv4.tcp_sack = 1net.ipv4.tcp_window_scaling = 1net.ipv4.tcp_rmem = 4096 87380 4194304net.ipv4.tcp_wmem = 4096 16384 4194304net.core.wmem_default = 8388608net.core.rmem_default = 8388608net.core.rmem_max = 16777216net.core.wmem_max = 16777216net.core.netdev_max_backlog = 262144net.core.somaxconn = 262144net.ipv4.tcp_max_orphans = 3276800net.ipv4.tcp_max_syn_backlog = 262144net.ipv4.tcp_timestamps = 0net.ipv4.tcp_synack_retries = 1net.ipv4.tcp_syn_retries = 1net.ipv4.tcp_tw_recycle = 1net.ipv4.tcp_tw_reuse = 1net.ipv4.tcp_mem = 94500000 915000000 927000000net.ipv4.tcp_fin_timeout = 1net.ipv4.tcp_keepalive_time = 30net.ipv4.ip_local_port_range = 1024 65000
3,系统连接数的优化
方法1.centos有效
ulimit -SHn 65535echo '* - nofile 65535' >>/etc/security/limits.conf
echo "* soft nproc 65535" >>/etc/security/limits.conf echo "* hard nproc 65535" >>/etc/security/limits.confecho "* soft nofile 65535" >>/etc/security/limits.confecho "* hard nofile 65535" >>/etc/security/limits.conf
方法2:
在/etc/profile 中增加一行 ulimit -SHn 65535 # debian中有效.
一个简单的nginx配置
user www www;worker_processes 8;worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000;error_log /www/log/nginx_error.log crit;pid /usr/local/nginx/nginx.pid;worker_rlimit_nofile 204800;events { use epoll; worker_connections 204800;}http { include mime.types; default_type application/octet-stream; charset utf-8; server_names_hash_bucket_size 128; client_header_buffer_size 2k; large_client_header_buffers 4 4k; client_max_body_size 8m; sendfile on; tcp_nopush on; keepalive_timeout 60; fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10m inactive=5m; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; fastcgi_buffer_size 4k; fastcgi_buffers 8 4k; fastcgi_busy_buffers_size 8k; fastcgi_temp_file_write_size 8k; fastcgi_cache TEST; fastcgi_cache_valid 200 302 1h; fastcgi_cache_valid 301 1d; fastcgi_cache_valid any 1m; fastcgi_cache_min_uses 1; fastcgi_cache_use_stale error timeout invalid_header http_500; open_file_cache max=204800 inactive=20s; open_file_cache_min_uses 1; open_file_cache_valid 30s; tcp_nodelay on; gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_http_version 1.0; gzip_comp_level 2; gzip_types text/plain application/x-javascript text/css application/xml; gzip_vary on; server { listen 8080; server_name backup.aiju.com; index index.php index.htm; root /www/html/; location /status { stub_status on; } location ~ .*\.(php|php5)?$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fcgi.conf; } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$ { expires 30d; } log_format access ‘$remote_addr — $remote_user [$time_local] “$request” ‘ ‘$status $body_bytes_sent “$http_referer” ‘ ‘”$http_user_agent” $http_x_forwarded_for’; access_log /www/log/access.log access; }}
关于FastCGI 的几个指令
fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=TEST:10minactive=5m;#这个指令为FastCGI 缓存指定一个路径,目录结构等级,关键字区域存储时间和非活动删除时间。fastcgi_connect_timeout 300;#指定连接到后端FastCGI 的超时时间。fastcgi_send_timeout 300;#向FastCGI 传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI 传送请求的超时时间。fastcgi_read_timeout 300;#接收FastCGI 应答的超时时间,这个值是指已经完成两次握手后接收FastCGI 应答的超时时间。fastcgi_buffer_size 4k;#指定读取FastCGI 应答第一部分需要用多大的缓冲区,一般第一部分应答不会超过1k,由于页面大小为4k,所以这里设置为4k。fastcgi_buffers 8 4k;#指定本地需要用多少和多大的缓冲区来缓冲FastCGI 的应答。fastcgi_busy_buffers_size 8k;#这个指令我也不知道是做什么用,只知道默认值是fastcgi_buffers 的两倍。fastcgi_temp_file_write_size 8k;#在写入fastcgi_temp_path 时将用多大的数据块,默认值是fastcgi_buffers 的两倍。fastcgi_cache TEST#开启FastCGI 缓存并且为其制定一个名称。个人感觉开启缓存非常有用,可以有效降低CPU 负载,并且防止502 错误。fastcgi_cache_valid 200 302 1h;fastcgi_cache_valid 301 1d;fastcgi_cache_valid any 1m;#为指定的应答代码指定缓存时间,如上例中将200,302 应答缓存一小时,301 应答缓存1 天,其他为1 分钟。fastcgi_cache_min_uses 1;#缓存在fastcgi_cache_path 指令inactive 参数值时间内的最少使用次数,如上例,如果在5 分钟内某文件1 次也没有被使用,那么这个文件将被移除。fastcgi_cache_use_stale error timeout invalid_header http_500;#不知道这个参数的作用,猜想应该是让nginx 知道哪些类型的缓存是没用的。
以上为nginx 中FastCGI 相关参数,另外,FastCGI 自身也有一些配置需要进行优化,如果你使用php-fpm 来管理FastCGI,可以修改配置文件中的值:
60#同时处理的并发请求数,即它将开启最多60 个子线程来处理并发连接。102400#最多打开文件数。204800#每个进程在重置之前能够执行的最多请求数。
fastcgi图解
参考1
参考2
nginx简单的负载均衡
upstream www { server 192.168.10.201:80 weight=80; server 192.168.10.202:80 weight=100; server 192.168.10.203:80 weight=80; server 192.168.10.204:80 weight=60;}server{ listen 80; server_name maotai.com www.maotai.com; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://www; }}
调度模式
1.轮询(默认方式)
每个请求按时间顺序分配到后端服务器,如果后端服务器down掉,会自动剔除。
2.weight
设置定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的场景。
upstream bakend { server 192.168.10.201:80 weight=100; server 192.168.10.202:80 weight=120; }
3.ip_hash
按访问ip的hash结果分配,每个IP固定访问一个后端服务器,可以解决session的问题。
upstream resinserver { ip_hash; server 192.168.10.201:80; server 192.168.10.202:80;}
4.按后端服务器的响应时间分配请求,响应时间短的优先分配。
upstream resinserver{ server 192.168.10.201:80; server 192.168.10.202:80; fair;}
5.url_hash
在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法
upstream resinserver{ server 192.168.10.201:80; server 192.168.10.202:80; hash $request_uri; hash_method crc32;}
定义负载均衡设备的状态
upstream seanzhau.com { ip_hash; server 192.168.10.201:80 down; server 192.168.10.202:80 weight=2; server 192.168.10.203:80 max_fails=3 fail_timeout=300; server 192.168.10.204:80 backup;}
状态含义:
- down - 指定server离线,不参与负载
- weight - 指定server的权重,weight越大,负载的权重就越大。默认为1。
- max_fails - 允许请求失败的次数,当超过最大次数时,返回proxy_next_upstream模块定义的错误。默认为1。
- fail_timeout - max_fails次失败后,暂停的时间。
- backup - 当非backup和down状态的server处于繁忙的时,请求backup机器。
nginx支持同时设置多组的负载均衡,用来给不用的server来使用。- client_body_in_file_only 设置为On,将client post过来的数据记录到文件中用来做debug。
- client_body_temp_path 设置记录文件的目录,可以设置最多3层目录。
- location 对URL进行匹配,进行重定向或者进行新的反向代理
动静分离
#php动态资源负载均衡upstream php { server 192.168.10.201:80; server 192.168.10.202:80;}#静态资源负载均衡upstream static { server 192.168.10.211:80; server 192.168.10.212:80;}server{ listen 80; server_name seanzhau.com; #php动态资源反向代理 location ~ \.php$ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://php; } #静态资源反向代理,默认所有请求转发静态资源负载均衡 location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://static; }}
nginx常用: web反向代理服务
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; root /opt/webapps/; index index.html index.htm; access_log /data/logs/nginx/seanzhau.com.log; #Web反向代理服务 location / { proxy_store off; proxy_redirect off; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_pass http://localhost:8080/; }}
nginx常用: WebSockets反向代理服务
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; root /opt/webapps/; index index.html index.htm; access_log /data/logs/nginx/seanzhau.com.log; #WebSockets反向代理服务 location / { proxy_store off; proxy_redirect off; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://localhost:8080/; }}
nginx常用: 简单的负载均衡
upstream www { #不配置调度方式,默认使用轮询。其他模式:ip_hash、url_hash、fair server 192.168.10.201:80 weight=100; server 192.168.10.202:80 weight=120; server 192.168.10.203:80 weight=100; server 192.168.10.204:80 weight=80;}server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; index index.html index.htm; access_log /data/logs/nginx/seanzhau.com.log; #Web反向代理服务 location / { proxy_store off; proxy_redirect off; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_pass http://www; }}
nginx status配置
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; location /nginx_status { stub_status on; access_log off; }}
SSL证书配置
[root@seanzhau.com ~]# cd /etc/nginx[root@seanzhau.com ~]# openssl genrsa -des3 -out server.key 1024[root@seanzhau.com ~]# openssl req -new -key server.key -out server.csr[root@seanzhau.com ~]# cp server.key server.key.org[root@seanzhau.com ~]# openssl rsa -in server.key.org -out server.key[root@seanzhau.com ~]# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt[root@seanzhau.com ~]# vim conf.d/web.confserver { listen 80 default_server; server_name _; rewrite ^(.*) https://$server_name$1 permanent;}server { listen 443 default_server; server_name seanzhau.com www.seanzhau.com; root /opt/webapps/; index index.html index.htm; access_log /data/logs/nginx/seanzhau.com.log; ssl on; ssl_certificate /etc/nginx/server.crt; ssl_certificate_key /etc/nginx/server.key; ssl_protocols SSLv2 SSLv3 TLSv1; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; location / { proxy_store off; proxy_redirect off; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_pass http://localhost:8080/; }}
限制IP访问
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; #限制IP访问整个web allow 100.100.100.0/24; deny all; #限制IP访问/photo location /photo { allow 200.200.200.200/32; deny all; } #限制访问密码 location /photo { auth_basic “C1G_ADMIN”; auth_basic_user_file htpasswd; }}
限制访问目录
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; #单目录限制 location ~ ^/data { deny all; } #多目录限制 location ~ ^/(cron|templates)/ { deny all; break; }}
限制非法域名访问
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; #限制非法域名访问 if ( $host != $server_name ){ return 403; }}
限制某一段时间内IP访问次数
#以用户二进制IP定义三个漏桶:滴落速率1-3req/sec,桶空间1m。#1M能保持大约16000个IP状态limit_req_zone $binary_remote_addr zone=qps1:1m rate=1r/s;server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; #速率qps=1,峰值burst=5,延迟请求 #严格按照漏桶速率qps=1处理每秒请求,在峰值burst=5以内的并发请求,会被挂起,超出请求数限制则直接返回503 # 例1:发起一个并发请求=6,拒绝1个,处理1个,进入延迟队列4个: # time request refuse sucess delay # 00:01 6 1 1 4 # 00:02 0 0 1 3 # 00:03 0 0 1 2 # 00:04 0 0 1 1 # 00:05 0 0 1 0 location /delay { limit_req zone=qps1 burst=5; } #速率qps=1,峰值burst=5,不延迟请求 #加了nodelay之后,漏桶控制一段时长内的平均qps = 漏桶速率,允许瞬时的峰值qps > 漏桶qps,所以峰值时的最高qps=(brust+qps-1)=5。请求不会被delay,要么处理,要么直接返回503 # 例2:每隔5秒发起一次达到峰值的并发请求,由于时间段内平均qps=1 所以仍然符合漏桶速率: # time request refuse sucess # 00:01 5 0 5 # 00:05 5 0 5 # 00:10 5 0 5 # 例3:连续每秒发起并发请求=5,由于时间段内平均qps>>1,超出的请求被拒绝: # time request refuse sucess # 00:01 5 0 5 # 00:02 5 4 1 # 00:03 5 4 1 location /nodelay { limit_req zone=qps1 burst=5 nodelay; }}
限制并发连接数
通过HTTPLimitZoneModule和HTTPCoreModule两个目录来限速。
#针对每个IP定义一个存储session状态的容器。#这个示例中定义了一个10m的容器,按照32bytes/session,可以处理320000个session。limit_zone zone $binary_remote_addr 10m;server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; location / { #限制每个IP并发10个连接 limit_conn zone 10; #每个连接限速300k。如果一个IP两个并发连接,那么这个IP就是限速limit_rate * 2 limit_rate 300k; }}
限制恶意cname
基于名称的虚拟服务器nginx请求匹配的时候是根据request的投信息host来判定哪个server处理请求!如果没有匹配到server_name,或者配置文件中不存在该server_name,那么nginx将会将这个请求转发给一个默认的server,如果你不想让它默认的,那么可以在listen指令中添加default_server参数指明。如下:
erver { listen 80 default_server; server_name _; return 403; }
或者
server { listen 80 default_server; server_name _; return 200 "{code:1, message:'domain config error!'}"; add_header Content-Type text/plain; }
注:0.8.21之后的nginx版本才支持default_server参数
nginx配置:将IP自动跳转到域名
server { listen 80 default_server; server_name 192.168.10.100; rewrite ^(.*) http://www.seanzhau.com permanent;}
nginx配置: http自动跳转到https
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; rewrite ^(.*) https://$server_name$1 permanent;}
利用error_page命令将497状态码的链接重定向
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; error_page 497 https://$server_name$uri?$args;}
nginx配置: 根域名自动跳到www
server { listen 80; server_name shizi.ml; rewrite ^/(.*)$ http://shizi.ml/$1 permanent;}server { listen 80; server_name www.shizi.ml; root /data/html/www; index index.html index.php index.htm; access_log logs/www_access.log;}
改写url
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; #设置访问/upload时访问/data/upload目录下的资源 #root指根目录,alias指某一个具体路径 location /upload { alias /data/upload; } #/abc/111/111.html改写为/def/111.html rewrite ^/(abc)/(\d+)/(.+) /def/$3 permanent; #目录对换 /123/abc ====> /abc?id=123 rewrite ^/(\d+)/(.+)/ /$2?id=$1 last; #访问的文件和目录不存在时重定向 if( !-e $request_filename ) { rewrite ^/(.*)$ index.html last; } #将多级目录下的文件转成一个文件,增强seo效果 #/job-123-456-789.html 指向/job/123/456/789.html rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last; #将根目录下某个文件夹指向2级目录 #如/zhjob/ 指向 /area/zhuhai/,如果将last改成permanent,那么浏览器地址栏显是/area/zhuhai/ rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;}
根据客户端语言区分访问路径
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; location / { set $lang zh_CN; rewrite ^/$ /zh_cn/ redirect; if ($http_accept_language ~* ^zh-tw) { set $lang zh_TW; rewrite ^/$ /zh_TW/ redirect; } if ($http_accept_language ~* ^en) { set $lang en_US; rewrite ^/$ /en_US/ redirect; } }
根据浏览器区分访问路径
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; location / { if( $http_user_agent ~ MSIE) rewrite ^(.*)$ /ie/$1 break; }}
访问后缀名配置
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; #禁止访问以.sh,.flv,.mp3为文件后缀名的文件 location ~ .*\.(sh|flv|mp3)$ { return 403; } #设置某些类型文件的浏览器缓存时间 location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 7d; }}
rewrtie四种flag
rewrtie四种flag:redirect、permanent、break和last。redirect和permanent是跳转型的flag,break和last后两种是代理型的flag。跳转型是指有客户端浏览器重新对新地址进行请求,代理型是在WEB服务器内部实现跳转的。
- redirect: 返回302临时重定向,浏览器地址会显示跳转后的URL地址。
- permanent: 返回301永久重定向,浏览器地址栏会显示跳转后的URL地址。
- last: 表示完成rewrite,浏览器地址栏URL地址不变。
- break: 完成匹配本条规则后,不再匹配后面的规则,浏览器地址栏URL地址不变。
跳转型URL会跳转地址,代理型URL地址不变。
server { listen 80 default_server; server_name seanzhau.com www.seanzhau.com; root /opt/webapps/static/; rewrite /img/old.jpg /images/new.jpg; rewrite /img/redirect.jpg /images/new.jpg redirect; rewrite /img/permanent.jpg /images/new.jpg permanent; rewrite /img/last.jpg /images/new.jpg last; rewrite /img/break.jpg /images/new.jpg break;}
注:使用root或proxy_pass指定源,break和last都可以,但是结果可能会有差别;使用alias指定源,必须使用last。
localtion正则匹配
location = / { # 精确匹配 / ,主机名后面不能带任何字符串 [ configuration A ]}location / { # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求 # 但是正则和最长字符串会优先匹配 [ configuration B ]}location /documents/ { # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索 # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条 [ configuration C ]}location ~ /documents/Abc { # 匹配任何以 /documents/Abc 开头的地址,匹配符合以后,还要继续往下搜索 # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条 [ configuration CC ]}location ^~ /images/ { # 匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条。 [ configuration D ]}location ~* \.(gif|jpg|jpeg)$ { # 匹配所有以 gif,jpg或jpeg 结尾的请求 # 然而,所有请求 /images/ 下的图片会被 config D 处理,因为 ^~ 到达不了这一条正则 [ configuration E ]}location /images/ { # 字符匹配到 /images/,继续往下,会发现 ^~ 存在 [ configuration F ]}location /images/abc { # 最长字符匹配到 /images/abc,继续往下,会发现 ^~ 存在 # F与G的放置顺序是没有关系的 [ configuration G ]}location ~ /images/abc/ { # 只有去掉 config D 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用 [ configuration H ]}location ~* /js/.*/\.js
常用正则
^~ 在字符串匹配后停止进行正则表达式的匹配= 表示精确匹配@ 表示自定义一个location,这个location不能被外界所访问,只能用于Nginx产生的子请求,主要为error_page和try_files。~ 区分大小写的匹配~* 不区分大小写的匹配!~ 区分大小写不匹配的!~* 不区分大小写不匹配的. 匹配除换行符以外的任意字符\w 匹配字母、数字、下划线或汉字的字符\s 匹配空白符\d 匹配数字\b 匹配单词的开始或结束^ 匹配字符串的开始$ 匹配字符串的结束[x] 匹配单个字符x[a-z] 匹配a-z小写字母的任意一个* 重复零次或多次+ 重复一次或多次? 重复零次或一次{n} 重复n次{n,} 重复n次或多次{n,m} 重复n到m次*? 重复任意次但尽可能少重复+? 重复1次或多次但尽可能少重复?? 重复0次或1次但尽可能少重复{n,m}? 重复n到m次但尽可能少重复{n,}? 重复n次以上但尽可能少重复\W 匹配不是字母、数字、下划线或汉字的字符\S 匹配不是空白符的字符\D 匹配非数字的字符\B 匹配不是单词开头或结束的位置[^x] 匹配除了x以外的任意字符[^aei] 匹配除了aei几个字母以外的任意字符捕获(exp) 匹配exp,并捕获文本到自动命名的组里(?<name>exp) 匹配exp,并捕获文本到名称为name的组里,也可以写成(?'name'exp)(?:exp) 匹配exp,不捕获匹配的文本,也不给此分组分配组号零宽断言(?=exp) 匹配exp前面的位置(?<=exp) 匹配exp后面的位置(?!exp) 匹配后面跟的不是exp的位置(?<!exp) 匹配前面不是exp的位置注释(?#comment) 这种类型的分组不对正则表达式的处理产生任何影响,用于提供注释让人阅读
支持apk和ipa应用下载
.apk 和 .ipa分别是android应用和ios应用的扩展名。
如果在浏览器下载这些文件为后缀的文件时,会自动重命名为zip文件。
当然可以下载后手动修改后缀,依然可以安装。
如果想下载后缀直接就是apk ipa的,可以修改 /usr/local/nginx/conf目录下的mime.types
增加如下配置,重启nginx生效
MIME配置最底部添加以下两种类型:
application/vnd.android.package-archive apk;application/iphone pxl ipa;#其他类型text/vnd.sun.j2me.app-descriptor jad;application/java-archive jar war ear;application/x-java-archive-diff jardiff;application/vnd.android.package-archive apk;application/vnd.ms-cab-compressed cab;application/octet-stream bin exe dll;application/vnd.symbian.install sis;x-epoc/x-sisx-app sisx;application/iphone pxl ipa;application/vnd.palm prc pdb;application/vnd.webos.ipk ipk;application/vnd.rim.cod cod;application/mrp mrp;x-nokia-widget wgz;application/octet-stream deb;
nginx配置示例
#定义Nginx运行的用户和用户组user www www;#nginx进程数,建议设置为等于CPU总核心数。worker_processes 8;#全局错误日志定义类型,[ debug | info | notice | warn | error | crit ]error_log /var/log/nginx/error.log info;#进程文件pid /var/run/nginx.pid;#一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。worker_rlimit_nofile 65535;#工作模式与连接数上限events{#参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。use epoll;#单个进程最大连接数(最大连接数=连接数*进程数)worker_connections 65535;}#设定http服务器http{include mime.types; #文件扩展名与文件类型映射表default_type application/octet-stream; #默认文件类型#charset utf-8; #默认编码server_names_hash_bucket_size 128; #服务器名字的hash表大小client_header_buffer_size 32k; #上传文件大小限制large_client_header_buffers 4 64k; #设定请求缓client_max_body_size 8m; #设定请求缓sendfile on; #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。tcp_nopush on; #防止网络阻塞tcp_nodelay on; #防止网络阻塞keepalive_timeout 120; #长连接超时时间,单位是秒#FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。fastcgi_connect_timeout 300;fastcgi_send_timeout 300;fastcgi_read_timeout 300;fastcgi_buffer_size 64k;fastcgi_buffers 4 64k;fastcgi_busy_buffers_size 128k;fastcgi_temp_file_write_size 128k;#gzip模块设置gzip on; #开启gzip压缩输出gzip_min_length 1k; #最小压缩文件大小gzip_buffers 4 16k; #压缩缓冲区gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)gzip_comp_level 2; #压缩等级gzip_types text/plain application/x-javascript text/css application/xml;#压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。gzip_vary on;#limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用upstream blog.ha97.com { #upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。 server 192.168.80.121:80 weight=3; server 192.168.80.122:80 weight=2; server 192.168.80.123:80 weight=3;}#虚拟主机的配置server{#监听端口listen 80;#域名可以有多个,用空格隔开server_name www.ha97.com ha97.com;index index.html index.htm index.php;root /data/www/ha97;location ~ .*\.(php|php5)?${ fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi.conf;}#图片缓存时间设置location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 10d; }#JS和CSS缓存时间设置location ~ .*\.(js|css)?$ { expires 1h; }#日志格式设定log_format access '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" $http_x_forwarded_for';#定义本虚拟主机的访问日志access_log /var/log/nginx/ha97access.log access;#对 "/" 启用反向代理location / { proxy_pass http://127.0.0.1:88; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #以下是一些反向代理的配置,可选。 proxy_set_header Host $host; client_max_body_size 10m; #允许客户端请求的最大单文件字节数 client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数, proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时) proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时) proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时) proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小 proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的设置 proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2) proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服务器传}#设定查看Nginx状态的地址location /NginxStatus { stub_status on; access_log on; auth_basic "NginxStatus"; auth_basic_user_file conf/htpasswd; #htpasswd文件的内容可以用apache提供的htpasswd工具来产生。}#本地动静分离反向代理配置#所有jsp的页面均交由tomcat或resin处理location ~ .(jsp|jspx|do)?$ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8080;}#所有静态文件由nginx直接读取不经过tomcat或resinlocation ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$ { expires 15d; } location ~ .*.(js|css)?$ { expires 1h; } }}
更详细的模块参数请参考:http://wiki.nginx.org/Main
- [svc]nginx常用功能配置
- 【Nginx】常用功能配置
- Nginx常用功能详解
- Nginx的常用配置
- Nginx 常用配置
- 常用的nginx 配置
- Nginx常用配置实例
- nginx 常用配置
- nginx常用配置
- nginx常用代理配置
- Nginx常用配置总结
- Nginx常用配置
- nginx常用代理配置
- nginx 常用配置
- nginx虚拟主机常用配置
- nginx常用配置
- Nginx 常用配置
- Nginx常用代理配置
- 正则表达式
- Android再按一次退出
- CocoaPods创建私有Pod库方法总结
- 【面向对象语言系列】关于C# 设计模式,你需要知道的事
- 智能合约源文件的基本要素
- [svc]nginx常用功能配置
- qsort和sort的区别
- 用python-pandas作图矩阵
- ios横竖屏转换相关<全屏播放界面处理>
- emd-build.sh
- BootStrap框架学习-下拉款Select搜索功能
- PLSQL创建表空间并且导入.dmp文件
- Activity 生命周期
- 支付宝电脑网站支付,也就是老版的即时到账