以下为字符串匹配操作符:
~ 为区分大小写匹配
~* 为不区分大小写匹配
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配
1: 限制某些类型的客户端的访问
location / { if ($http_user_agent ~ MSIE) { return 503; } }#限制IE访问
如果把MSIE改成 Mozilla 就基本上把IE和firefox这样pc浏览器限制了
2和3主要是针对盗链做处理
2:针对不同的文件类型
location ~ .*\.(wma|wmv|asf|mp3|mmf|zip|rar|jpg|gif|png|swf|flv)$ { if ($http_referer ~* hecks.tk) { #rewrite ^/ http://www.hecks.tk/403.html; return 403; } }
3:针对不同的目录
location /img/ { root /data/img/; if ($http_referer ~* hecks.tk) { rewrite ^/ http://www.hecks.tk/images/error.gif #return 403; } }
另外的一个nginx配置例子
worker_processes 2; #工作进程数,在网上看到说最优是cpu的二倍
error_log current_path/log/nginx.error.log debug; pid shared_path/pids/nginx.pid; events { worker_connections 1024;#最大连接数 } http { include /usr/local/nginx/conf/mime.types;#content type 文件 default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] $status ' '"$request" $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log current_path/log/nginx.access.log main;#log文件存放地方 sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 70; gzip on; gzip_min_length 1000; gzip_buffers 4 8k; gzip_comp_level 9; gzip_proxied any; gzip_types application/xml application/javascript application/x-javascript application/atom+xml application/rss+xml; gzip_types text/css text/html text/javascript text/js text/plain text/xml; upstream mongrel {#proxy 负载均衡配置 server 127.0.0.1:8000;#服务器1 server 127.0.0.1:8001;#服务器2 } server { listen 80; server_name hecks.tk www.hecks.tk; root current_path/public; index index.html index.htm; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host "www.hecks.tk"; proxy_redirect false; proxy_max_temp_file_size 0; # rewrite 'hecks.tk' -> 'www.hecks.tk' if ($host = 'hecks.tk' ) { rewrite ^/(.*)$ http://www.hecks.tk/$1 permanent; } #如果静态文件存在服务器,则跳过rewrite规则 if (-f $request_filename) { expires max; break; } # redirect feed requests to feedburner, unless its the feedburner agent if ($http_user_agent !~ FeedBurner) { rewrite ^/feed/atom.xml$ http://feeds.feedburner.com/hecks; } if (-f $request_filename/index.html) { expires 7d; rewrite (.*) $1/index.html break; } # support rails page caching if (-f $request_filename.html) { rewrite (.*) $1.html break; } # pass it onto upstream mongrel cluster if (!-f $request_filename) { proxy_pass http://www.hecks.tk; break; } } location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mov).*?$ { root current_path/public; if (!-f $request_filename) { proxy_pass http://www.hecks.tk; break; } } error_page 500 502 503 504 /50x.html; location = /50x.html { root current_path/public; } } }