Ubuntu系统中部署Nginx实现网站负载均衡
Nginx是一个高性能的HTTP和反向代理服务器,在实际的开发过程中会经常使用他的反向代理功能对流量大网站今天负载均衡,之前也介绍过,关于Nginx在Windows中的配置教程,不过在Windows下Nginx的性能相对来说不是很好,不过在开发过程中部署在windows上进行测试还是很方便的,点击进入:windows中部署Nginx教程,实际过程中一般要采用部署在Linux系统中稳定性和性能会好很多,本文采用Linux的发行版本Ubuntu进行详细说明。
首先更新Ubuntu自带的软件源:
apt-get update
安装nginx
apt-get install nginx
过程中会提示消耗XXX空间,直接点击Y确定即可
编辑Nginx配置文件
vim /etc/nginx/nginx.conf
配置文件默认情况下只是一些默认的数据,直接删除即可
1.基本的网站反向代理,以及对网站指定目录进行单独代理
user www-data;
worker_processes 32;
pid /run/nginx.pid;
events {
worker_connections 65535;
}
http {
server_names_hash_bucket_size 1024; #防止URL太长导致报错
proxy_buffer_size 1024k;
proxy_buffers 32 1024k;
client_max_body_size 1024m; #设置最大传入数据
access_log off;
server{
listen 80;
server_name www.xxx.com;
location / {
proxy_pass http://10.0.0.2;
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_set_header Cookie $http_cookie;
proxy_set_header Via "nginx";
}
//对指定目录进行独立的服务器代理
location /img/ {
proxy_pass http://10.0.0.3/;
proxy_set_header Host img.xxx.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Cookie $http_cookie;
proxy_set_header Via "nginx";
}
}
}
2.网站拥有多台后端程序服务器进行负载均衡
user www-data;
worker_processes 32;
pid /run/nginx.pid;
events {
worker_connections 40960;
}
http {
server_names_hash_bucket_size 128;
proxy_buffer_size 64k;
proxy_buffers 8 64k;
upstream www.xxx.com.nb {
ip_hash;
server 10.0.0.5;
server 10.0.0.6;
}
server{
listen 80;
server_name www.xxx.com;
location / {
proxy_pass http://www.xxx.com.nb;
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_set_header Cookie $http_cookie;
proxy_set_header Via "nginx";
}
location /css/ {
proxy_pass http://10.0.0.8/;
proxy_set_header Host img.xxx.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Cookie $http_cookie;
proxy_set_header Via "nginx";
}
}
}
启动Nginx
/etc/init.d/nginx start
重载刷新配置
/etc/init.d/nginx reload