1、正向代理
# http方式
server {
resolver 114.114.114.114; # 添加DNS服务器IP地址
listen 80;
server_name localhost;
location / {
proxy_pass http://$host$request_uri; #设定代理服务器的协议和地址
proxy_set_header HOST $host;
proxy_buffers 256 4k;
proxy_max_temp_file_size 0k;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_next_upstream error timeout invalid_header http_502;
}
}
# https方式只需要将端口改为443和proxy_pass后面的http改变为https即可
访问测试:
[root@k8s-node1 conf]# curl -I --proxy 192.168.6.21:80 www.baidu.com
HTTP/1.1 200 OK
Server: nginx/1.20.2
Date: Fri, 06 May 2022 02:18:48 GMT
Content-Type: text/html
Content-Length: 277
Connection: keep-alive
Accept-Ranges: bytes
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Etag: "575e1f60-115"
Last-Modified: Mon, 13 Jun 2016 02:50:08 GMT
Pragma: no-cache
设置Linux客户端全局代理
vim /etc/profile.d/my_env.sh
# 添加如下内容
export http_proxy='192.168.6.21:80'
#export http_proxy='192.168.6.21:443'
#export ftp_proxy='192.168.6.21:80'
source /etc/profile
# 访问测试
[root@k8s-node1 conf]# curl -I www.baidu.com:80
HTTP/1.1 200 OK
Server: nginx/1.20.2
Date: Fri, 06 May 2022 02:28:48 GMT
Content-Type: text/html
Content-Length: 277
Connection: keep-alive
Accept-Ranges: bytes
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Etag: "575e1f60-115"
Last-Modified: Mon, 13 Jun 2016 02:50:08 GMT
Pragma: no-cache
2、反向代理
反向代理时:proxy_pass后面的单个URL地址必须是完全的域名
比如:http://www.baidu.com和http://baidu.com
前者代理返回状态吗200,后者返回状态码302 Moved Temporarily (from disk cache),并在地址栏更改url为实际www.baidu.com
并且反向代理中不支持https,需要域名对应的证书
location / {
proxy_pass http://www.baidu.com;
#root html;
#index index.html index.htm;
}
3、负载均衡和反向代理
使用upstream定义一组服务器和server同一级别
upstream httpds {
server 192.168.6.21:8081;
server 192.168.6.21:8082;
server 192.168.6.20;
server 192.168.6.20:8081;
}
修改location的proxy_pass
location / {
proxy_pass http://httpds;
#root html;
#index index.html index.htm;
}