5. Nginx配置文件精讲二
#这里为后端服务器wugk应用集群配置,根据后端实际情况修改即可,tdt_wugk为负载均衡名称,可以任意指定
#但必须跟vhosts.conf虚拟主机的pass段一致,否则不能转发后端的请求。weight配置权重,在fail_timeout内检查max_fails次数,失败则剔除均衡。
upstream tdt_wugk {
server 127.0.0.1:8080 weight=1 max_fails=2 fail_timeout=30s;
server 127.0.0.1:8081 weight=1 max_fails=2 fail_timeout=30s;
}
#虚拟主机配置
server {
#侦听80端口
listen 80;
#定义使用www.wuguangke.cn访问
server_name www.wuguangke.cn;
#设定本虚拟主机的访问日志
access_log logs/access.log main;
root /data/webapps/wugk; #定义服务器的默认网站根目录位置
index index.php index.html index.htm; #定义首页索引文件的名称
#默认请求
location ~ /{
root /data/www/wugk; #定义服务器的默认网站根目录位置
index index.php index.html index.htm; #定义首页索引文件的名称
#以下是一些反向代理的配置.
proxy_next_upstream http_502 http_504 error timeout invalid_header;
#如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。
proxy_redirect off;
#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
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://tdt_wugk; #请求转向后端定义的均衡模块
}
#配置Nginx动静分离,定义的静态页面直接从Nginx发布目录读取。
location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$
{
root /data/www/wugk;
#expires定义用户浏览器缓存的时间为3天,如果静态页面不常更新,可以设置更长,这样可以节省带宽和缓解服务器的压力。
expires 30d;
}
#PHP脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
location ~ \.php$ {
root /root;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www/wugk$fastcgi_script_name;
include fastcgi_params;
}
#设定查看Nginx状态的地址
location /NginxStatus {
stub_status on;
}
}
}
6. 实战线上Nginx多站点配置
在真实的服务器环境,为了充分利用服务器资源,一台nginx web服务器同时会配置N个虚拟域名主机,即多个域名对于同样一个80端口。然后服务器IP数量很多,也可以配置基于多个IP对应同一个端口。
vi修改nginx.conf server段配置内容如下:
#virtual hosts config 2014/5/18
server {
listen 80;
server_name www.a.com;
#access_log logs/host.access.log main;
location / {
root html/a;
index index.html index.htm;
}
server {
listen 80;
server_name www.b.com;
#access_log logs/host.access.log main;
location / {
root html/b;
index index.html index.htm;
}
创建两个不同的目录mkdir –p /usr/local/nginx/html/{a,b},然后分别在两个目录创建两个不同的index.html网站页面即可。通过客户端配置hosts指向两个域名,然后在IE浏览器访问测试效果。