一、NGINX简介
Nginx是一款高性能的http服务器和反向代理服务器,同时支持IMAP/POP3/SMPT代理服务。Nginx是由c语言编写的。
Nginx的应用场景
- http服务器:Nginx是一个http服务,可以独立提供http服务。可以做网页静态服务器。
- 虚拟主机:可以在一台服务器虚拟出多态网站。例如个人网站使用的虚拟机。
- 反向代理,负载均衡:当网站的访问量达到一定程度之后,单台服务器不能满足用户请求,需要多台服务器集群,可以使用Nginx做反向代理。并且多台服务器可以平均分担负载,不会因为某台服务器负载过高而宕机,或者使某台服务器闲置。
二、NGINX配置
#用户
#user nobody;
#进程数
worker_processes 1;
#日志记录
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#进程ID
#pid logs/nginx.pid;
events {
# Nginx的工作模型,在日志中可以看到
use epoll;
#每个进程的最大连接数
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
#超时设置
keepalive_timeout 65;
#gzip on;
server {
#监听端口
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
# / 代表所有
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
修改配置文件后,重新载入配置文件
./nginx -s reload
三、NGINX代理模式
正向代理
VPN就是正向代理的一个例子。正向代理服务器位于客户端和服务器之间。为了向服务器获取数据,客户端要向代理服务器发送一个请求,并指定目标服务器。代理服务器将目标服务器返回的数据转交给客户端。客户端要进行一些正向代理的设置。
反向代理
在反向代理中,客户端对代理是无感知的,因为客户端不需要任何配置就可以访问。客户端将数据发送到反向代理服务器,由反向代理服务器选择目标服务器,获取数据后再返回给客户端。此时,反向代理服务器和目标服务器对外是一个服务器,暴露的是代理服务器的地址,隐藏了真实服务器的IP地址。
正向代理与反向代理的区别:正向代理代理客户端,反向代理代理服务器。
四、NGINX负载均衡方式
轮询
轮询是Nginx负载均衡的默认配置方式。轮询是指所有请求安照时间顺序分配到不同服务器上,如果服务器down掉,可以自动剔除。如下配置后轮询10001和10002服务。
权重
指定每个服务器的权重,权重与访问量成正比。常用于后端服务器的性能不统一,将性能好的服务器分配的权重高一些。如下配置10002服务器的访问率是10001服务器的2倍。
iphash
根据客户端的IP的hash结果分配将要访问的服务器,这样固定的访客可以访问固定的服务器。iphash可以和权重配合使用。
最少连接数
将请求分配到连接最少的服务器上。
fair
按后端服务器的响应时间分配请求,响应时间短的优先分配。