Nginx反向代理
反向代理典型应用场景
反向代理的典型用途是将防火墙后面的服务器提供给 Internet 用户访问,加强安全防护。反向代理还可以为后端的多台服务器提供负载均衡,或为后端较慢的服务器提供缓冲服务。
例子
下面我们就定义两个反响代理的例子,代理范围两部分:当用户访问跟路径的时候,代理返回github首页;当用户访问跟路径下的aaa时返回github上的一个文件。
worker_processes 1;
error_log logs/error.log info;
events {
worker_connections 1024;
}
http {
open_file_cache max=204800 inactive=20s;
open_file_cache_min_uses 1;
open_file_cache_valid 30s;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain;
log_format myformat '$remote_addr $status $time_local';
access_log logs/access.log myformat;
server {
listen 8080;
charset utf-8;
location = / {
proxy_pass https://github.com/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header X-Forworded-For $proxy_add_x_forwarded_for;
}
location = /aaa {
proxy_pass https://github.com/aaa;
proxy_set_header X-Real_IP $remote_addr;
proxy_set_header X-Forworded-For $proxy_add_x_forwarded_for;
}
}
}
可以看到结果就想我们想象的一样,访问localhost:8080返回的是github主页,访问localhost:8080/aaa返回的时github上一个叫aaa的用户的首页。
正常情况下反响代理不会转发host头部如果有需要就加上proxy_set_header Host $host;
。另外,如果原始服务器需要统计请求来源,就需要加上proxy_set_header X-Real_IP $remote_addr;
这句话,这样原始服务器就知道来源ip是什么同样X-Forworded-For
,可以统计从哪里跳转过来的,以便做安全策略和统计。