nginx的匹配规则
1 2 3 4 5 6 7 8 9
| ~ ~* ^~ = @
~ *.(gif|jpg|jpeg|png|bmp|swf)$
|
nginx常用代理配置参数
1 2 3 4 5 6
| location / { proxy_pass http://xxxx; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
nginx配置ws协议访问
在location配置段内填写如下参数
1 2 3
| proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";
|
rewrite
1 2 3
| location / { rewrite ^(.*) http://new.domain.com permanent; }
|
匹配url开头代理
1 2 3 4
| location ~* (^/api){ proxy_pass http://$ipnew:port; ... }
|
根据各种请求参数匹配进行跳转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| location ~* (^/api){ if ( $http_user_agent ~* "iPhone|Android" ) { rewrite (.*) http://www.xxx.com/mobile$1 permanent; break; } if ( $http_referer ~* "/phone/w/|/p2/" ) { proxy_pass proxy_pass http://$ipnew02:port; add_header Cache-Control no-store; break; } proxy_pass http://$ipnew:port; include $nginx_prefix/conf/proxy.conf; }
|
nginx多重条件匹配
1 2 3 4 5 6 7 8 9 10 11
| 匹配当请求是"POST"请求且是jpg结尾的文件时,返回503 set $flag 0; if ( $request_method = "POST" ) { set $flag "${flag}1"; } if ( $url ~ \.jpg$ ) { set $flag "${flag}2"; } if ( $flag = "012" ) { return 503; }
|
nginx配置ssl证书
在具体配置段内添加
1 2 3 4 5 6 7 8
| ssl on; ssl_certificate ssl.crt; ssl_certificate_key ssl.key; ssl_session_timeout 5m; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; ssl_protocols TLSv1 TLSv1.1 TLSv1.2;。 ssl_prefer_server_ciphers on;
|
限制指定IP访问
具体配置如下
在nginx的代理配置文件中添加如下配置,返回状态码403
1 2 3 4 5 6 7 8 9 10 11
| set $http_status_num 0; if ($http_x_forwarded_for = '172.16.1.35') { set $http_status_num 1; } if ($http_x_forwarded_for = '172.16.1.142') { set $http_status_num 1; } if ($http_status_num != 1) { return 403; }
|
Nginx常见问题—alias和root的区别
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| server { listen 80; index index.html; location /request_path/code/ { alias /local_path/code; } }
server { listen 80; index index.html; location /request_path/code/ { root /local_path/code; } }
|
在上面配置文件中,如果使用的是alias,那么实际请求路径为/local_path/code;如果使用的是root,实际请求路径为/local_path/code/request_path/code。也就是说root的请求路径是root+location的地址,而alias则是跳转到alias所指定的目录
nginx日志切割方法
新建nginx日志分割脚本
1 2 3 4 5 6
| vim nginx_log_cut.sh
Logs_PATH=/usr/local/nginx/logs/access Yesterday=$(date -d "yesterday" +%Y%m%d) mv ${Logs_PATH}/access.log ${Logs_PATH}/access_${Yesterday}.log kill -USR1 $(cat /var/run/nginx.pid)
|
添加计划任务,每天的0点执行分割
1 2 3
| crontab -e
0 0 * * * /bin/bash /$scripts_path/nginx_log_cut.sh
|