又一枚神器:nginx
一直听说过nginx的大名,也自己装过,但是未直接使用其各种牛X的功能。
今天试用了一下,只能用两字感叹:牛逼!比如它提供的配置检查功能,真是贴心极了,又比如我想要的静态内容浏览器端缓存功能,动态内容转发功能,都极其简单,不得不感叹啊。
我们先来看看nginx的各种能力,然后列出一些收集的nginx各项能力的配置以及一些调优的文章,供日后备用。
ginx我就不介绍了,大家都知道。其工作原理参考这里,里面也讲了nginx的模块开发http://blog.codinglabs.org/articles/intro-of-nginx-module-development.html
安装也略过,apt-get可以轻松搞定。
ginx的能力一览:
1. 负载均衡
2. 反向代理:整合后端的各种服务器和语言(PHP, PERL, TOMCAT),反向代理缓存,静态内容浏览器缓存,动静分离
3. 安全:防盗链,防爬虫,HTTPS
4. 其它:同memcache结合干各种层次的缓存,限速,自动裁剪图片,请求合并,集成lua,玩法太多了……
这边列举一些常见的配置(均来源于网上),方便日后使用:
ginx配置测试(假设nginx已经加入path,下同): nginx -t
ginx平滑重启:首先找到master processor的pid,简单点用ps -ef | grep nginx,然后kill -HUP pid
负载均衡
[plain] view plaincopy
http { upstream myserver { server 192.168.12.181:80 weight=3 max_fails=3 fail_timeout=20s; server 192.168.12.182:80 weight=1 max_fails=3 fail_timeout=20s; server 192.168.12.183:80 weight=4 max_fails=3 fail_timeout=20s; } server { listen 80; server_name www.domain.com 192.168.12.189; index index.htm index.html; root /ixdba/web/wwwroot; location / { proxy_pass http://myserver; proxy_next_upstream http_500 http_502 http_503 error timeout invalid_header; include /opt/nginx/conf/proxy.conf; } } }
虚拟主机
[plain] view plaincopy
http { server { listen 80; server_name www.domain1.com; access_log logs/domain1.access.log main; location / { index index.html; root /web/www/domain1.com/htdocs; } } server { listen 80; server_name www.domain2.com; access_log logs/domain2.access.log main; location / { index index.html; root /web/www/domain2.com/htdocs; } } include /opt/nginx/conf/vhosts/www.domain2.com.conf; } [plain] view plaincopy server { listen 80; server_name www.domain3.com; access_log logs/domain3.access.log main; location / { index index.html; root /web/www/domain3.com/htdocs; } }
反向代理,整合tomcat
[plain] view plaincopy
location / { proxy_pass http://localhost:8080; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forworded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; }
反向代理,分离静态页面,并设置静态页面缓存时间(if-modify-since)
[plain] view plaincopy
location /img/ { alias /www/root/img/; expires 10d; }
设置Cache-Control
[plain] view plaincopy
add_header Cache-Control max-age=3600
安全,防盗链
[plain] view plaincopy
location ~* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ { valid_referers none blocked *.ixdba1.net ixdba1.net; if ($invalid_referer) { rewrite ^/ http://www.ixdba.net/img/error.gif; #return 403; } } location /images { root /opt/nginx/html; valid_referers none blocked *.ixdba1.net ixdba1.net; if ($invalid_referer) { return 403; } }
安全,HTTPShttp://nginx.org/cn/docs/http/configuring_https_servers.html