About
nginx [engine x] is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server, originally written by Igor Sysoev. For a long time, it has been running on many heavily loaded Russian sites including Yandex, Mail.Ru, VK, and Rambler. According to Netcraft, nginx served or proxied 28.50% busiest sites in March 2017. Here are some of the success stories: Netflix, Wordpress.com, FastMail.FM.
安装
CentOS 7:
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx # 可选
配置文件
/etc/nginx/
├── conf.d/
├── default.d/
├── fastcgi.conf
├── fastcgi.conf.default
├── fastcgi_params
├── fastcgi_params.default
├── koi-utf
├── koi-win
├── mime.types
├── mime.types.default
├── nginx.conf
├── nginx.conf.default
├── scgi_params
├── scgi_params.default
├── uwsgi_params
├── uwsgi_params.default
└── win-utf
网页打不开
一般是防火墙或者 SELinux 引起的,先尝试:
su - root
setenforce 0 # 关闭 SElinux (当 getenforce 不是 Disable 时执行)
iptables -F # 关闭防火墙 (一般报错是 ERR_CONNECTION_REFUSED)
负载均衡
最简单的配置,如下:
# /etc/nginx/nginx.conf
http {
# ...
upstream backend {
server 192.168.100.4:8000;
server 192.168.100.5:8000;
server 192.168.100.6:8000;
}
server {
listen 8000;
location / {
proxy_pass http://backend;
}
}
}
proxy_pass
必须以 http://
开头,会检查格式。
两个 backend
是对应的,也可以替换为实际域名。
其它常用配置:
location / {
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_buffering off; # 是否将后端被代理机器的响应内容放入缓冲
}
测试方法:在后端的几台机器上放不同的首页,仅显示机器编号即可,每一次访问显示的编号都不相同才对,因为它使用的是轮流调度 (Round Robin) 方式。