location [ = | ~ | ~* | ^~ | @] /uri/ { configuration } location = /uri =开头表示精确前缀匹配,只有完全匹配才能生效。 location ^~ /uri ^~开头表示普通字符串匹配上以后不再进行正则匹配。 location ~ pattern ~开头表示区分大小写的正则匹配。 location ~* pattern ~*开头表示不区分大小写的正则匹配。 location /uri 不带任何修饰符,表示前缀匹配。 location / 通用匹配,任何未匹配到其他location的请求都会匹配到。 #实用三条规则 location = / { 直接proxy_pass转给后端,或root到静态文件 } location ^~ /static/ { root /web/static/; } 或 location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ { root /web/res/; } location / { proxy_pass http://host:port/; }
if ( !-f文件-d目录-e文件或目录-x是否可执行 $request_filename ) // =等 !=不等 ~* ^1[0-9]{10}$匹配 =''空 if ($http_user_agent ~ MSIE) { rewrite ^(.*)$ /msie/$1 break; } //如果UA包含"MSIE",rewrite请求到/msid/目录下 if ( $request_method = OPTIONS ) { return 200; } $args请求query参数,$http_cookie $content_type $scheme $server_protocol $document_uri location ~* \.(gif|jpg|png|swf|flv)$ { valid_referers none blocked www.jefflei.com www.leizhenfang.com; if ($invalid_referer) { return 404; } //防盗链 示例:http://localhost:88/test1/test2/test.php?a=b $host:localhost $server_port:88 $request_uri:/test1/test2/test.php?a=b $uri:/test1/test2/test.php,不带请求参数同$document_uri $document_root:/var/www/html $request_filename:/var/www/html/test1/test2/test.php
if ( $request_method = OPTIONS ) { add_header Access-Control-Allow-Origin $http_origin; add_header Access-Control-Allow-Credentials 'true'; add_header Access-Control-Allow-Methods 'GET, PUT, POST, DELETE, HEAD, OPTIONS'; add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; return 204; }
worker_connections会受系统FD限制,ulimit或worker_rlimit_nofile提升限值 error_log /dev/null emerg; 日志可用access_log off关闭,错误日志不支持off # nginx 与 upstream之间应配置长链接,数量建议为server数量*2,location需配置头,避免Connection: close upstream up { ip_hash; server ip:port; keepalive 2; } location / { proxy_http_version 1.1; proxy_set_header "Connection" ""; proxy_pass http://up; } # add_header Name value; 可以在location<server<http继承,但是若下级出现了add_header则不会合并上级已有的头 # 不要配置proxy_buffering off,默认开启缓存就好 # if内仅支持return和rewrite,建议用map $http_x_test $up { default "b"; "" "a"; },proxy_pass http://$up; # hash $binary_remote_addr consistent; 这个比ip_hash;更好