注意:nginx正向代理有缺陷,如果同时实现http和https正向代理请使用squid软件
(1)正反向代理
正向代理:实现客户端上网
反向代理:代理访问后端web服务器,
区别:正向代理的对象是客户端,反向代理的对象是服务器端
(2)nginx实现http正向代理
1.修改配置文件
#vim /usr/local/nginx/conf/nginx.conf
http {
include /usr/local/nginx/conf.d/*.conf
}
#mkdir /usr/local/nginx/conf.d
#vim /usr/local/nginx/conf.d/proxy.conf
server {
listen 8080;
resolver 114.114.114.114;
location / {
proxy_pass http://$http_host$request_uri;
}
}
#nginx -t
#nginx -s reload
2.搜狗浏览器代理设置
3.访问网易没有问题,但是https有问题,建议使用squid实现http和https的正向代理
(2)nginx实现反向代理
1.代理服务器配置
#vim /usr/local/nginx/conf/nginx.conf
http {
include /usr/local/nginx/conf.d/*.conf
}
#mkdir /usr/local/nginx/conf.d
#vim /usr/local/nginx/conf.d/proxy.conf //这里建议使用基于主机地址的反向代理
server {
listen 80;
server_name www.test.com;
location / {
proxy_pass http://192.9.191.31:80;
}
}
2.默认情况下后端web服务器获取的是代理服务器访问过来的ip地址,如果想获取客户端真实的ip地址,proxy_set_header3个配置
#vim /usr/local/nginx/conf.d/proxy.conf
server {
listen 80;
server_name www.test.com;
location / {
proxy_pass http://192.9.191.31:80;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
web服务器端日志配置,变量$http_x_forwarded_for代理服务器把客户端的ip通过这个变量传递给web服务器
#vim /usr/local/nginx/conf/nginx.conf
http {
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;
error_log logs/error.log;
}
web服务器验证:最后一列就是客户端的ip地址
原文地址:https://www.cnblogs.com/lovelinux199075/p/9061793.html
时间: 2024-10-12 08:41:58