最近,工作中遇到需要用到 Nginx 实现正向web代理和反向web代理的需求,其中反向web代理需要支持发送HTTP 和 HTTPS请求
1. 正向代理
1.1. 正向代理 流程
下面以访问百度为例解释正向代理过程:
- 客户将浏览器代理地址设置为代理服务器地址和服务端口;
- nginx 代理服务器配置代理服务;
- 客户通过浏览器的请求,都会先到达nginx服务器,在通过nginx 服务器转发到真实服务器;
1.2. 正向代理 配置
user root;
worker processes auto;
pid /tmp/nginx.pid;
error_log /tmp/error.log;
events {
fworker_connections 50000;
}
http {
access log off;
default_type application/octet-stream;
sendfile on;
keepalive timeout 65;
server{
client_max_body size 102400m;
resolver_timeout 20s;
listen 监听地址:监听端口;
proxy_connect;
proxy_connect allow all;
include /usr/local/nginx/conf/httproxy.conf;
}
}
2. 反向代理
2.1. 反向代理 流程
反向代理不需要修改浏览器代理地址,而是直接访问nginx提供的服务地址,所以需要在nginx 服务器上提前配置和代理的真实服务器地址,下面配置以百度为例。
2.2. 反向代理 配置
user root;
worker processes auto;
pid /tmp/nginx.pid;
error_log /tmp/error.log;
events {
fworker_connections 50000;
}
http {
access log off;
default_type application/octet-stream;
sendfile on;
keepalive timeout 65;
server{
client_max_body size 102400m;
resolver_timeout 20s;
listen 监听地址:监听端口;
proxy_connect;
proxy_connect allow all;
location /{
proxy_pass https://www.baidu.com;
}
}
}
2.3. 反向代理 HTTPS 配置
user root;
worker processes auto;
pid /tmp/nginx.pid;
error_log /tmp/error.log;
events {
fworker_connections 50000;
}
http {
access log off;
default_type application/octet-stream;
sendfile on;
keepalive timeout 65;
server{
client_max_body size 102400m;
resolver_timeout 20s;
listen 监听地址:监听端口 ssl;
ssl_session_timeout 5m;
ssl_session_tickets on;
ssl_session_cache shared:SSL:5m;
ssl_certificate 证书文件路径;
ssl_certificate_key 密钥文件路径;
ssl_crefer_server_ciphers on;
ssl_protocols TLSv1.2;
ssl_ciphers ECD+AESGCM:ECDH+AES256:!ECD+AES128:!DH+3DES:!3DES:!ADH:!AECDH:!MD5;
location /{
proxy_pass https://www.baidu.com;
}
}
}