Nginx代理和负载均衡
Nginx代理
代理是这样定义的:给某个对象提供一个代理对象,并由代理对象控制原对象的引用。相当于一个中间者。
用户和代理服务器相通,代理服务器和WEB服务器相通,用户可以通过代理服务器来访问WEB服务器
配置Nginx代理
1.修改虚拟主机配置文件
[root@antong ~]# vim /usr/local/nginx/conf/vhost/proxy.conf //加入以下内容
server
{
listen 80;
server_name ask.apelearn.com;
location /
{
proxy_pass http://47.104.7.242/; //WEB服务器的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;
}
}
2.测试
[root@antong ~]# curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.17.8</center>
</body>
</html>
[root@antong ~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@antong ~]# /usr/local/nginx/sbin/nginx -s reload
[root@antong ~]# curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
#
# robots.txt for MiWen
#
User-agent: *
Disallow: /?/admin/
Disallow: /?/people/
Disallow: /?/question/
Disallow: /account/
Disallow: /app/
Disallow: /cache/
Disallow: /install/
Disallow: /models/
Disallow: /crond/run/
Disallow: /search/
Disallow: /static/
Disallow: /setting/
Disallow: /system/
Disallow: /tmp/
Disallow: /themes/
Disallow: /uploads/
Disallow: /url-*
Disallow: /views/
Disallow: /*/ajax/
Nginx负载均衡
代理一台服务器为代理,代理两台以上就可以称作是负载均衡。
配置负载均衡
需要借助一个模块,这个模块叫upstream,可以定义多个ip
Nginx不支持代理https,server端口后面不能写43,据说新版本能够代理tcp。
1.修改虚拟主机配置文件
[root@antong ~]# vim /usr/local/nginx/conf/vhost/load.conf
upstream baidu
{
ip_hash; //后端如果有多台服务器,请求会到别的服务器上,利用ip_hash可以解决这个问题
server 110.242.68.3:80;
server 110.242.68.4:80;
}
server
{
listen 80;
server_name www.baidu.com;
location /
{
proxy_pass http://baidu;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
2.测试
[root@antong ~]# curl -x127.0.0.1:80 www.baidu.com
this is a default site.
[root@antong ~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@antong ~]# /usr/local/nginx/sbin/nginx -s reload
[root@antong ~]# curl -x127.0.0.1:80 www.baidu.com
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form>
···访问成功,以下省略