震惊了!!nginx代理还能这么用

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

通过nginx做反向代理相信大家都耳熟能详了,但是使用nginx做正向代理你玩过吗?

直接上结论,为什么使用nginx做正向代理。

nginx做正向代理的好处

  • 基于域名做白名单
  • 不用配置ssl证书!!!不用配置ssl证书!!!不用配置ssl证书!!!

初始化运行环境

安装必要的依赖组件,直接上脚本

1
2
shell复制代码yum -y update
yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel patch git

下载nginx支持代理的模块

1
2
3
shell复制代码mkdir /usr/local/nginx_modules
cd /usr/local/nginx_modules
git clone https://github.com/chobits/ngx_http_proxy_connect_module.git

安装nginx

下载并解压

1
2
3
shell复制代码wget http://nginx.org/download/nginx-1.19.8.tar.gz
tar -zxvf nginx-1.19.8.tar.gz
cd nginx-1.19.8/

安装补丁

1
shell复制代码patch -p1 < /usr/local/nginx_modules/ngx_http_proxy_connect_module/patch/proxy_connect_rewrite_1018.patch

创建运行nginx用户&用户组

1
2
shell复制代码groupadd www
useradd -g www www

开始安装nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
shell复制代码./configure \
--user=www \
--group=www \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_realip_module \
--with-threads \
--add-module=/usr/local/nginx_modules/ngx_http_proxy_connect_module

make

make install

到此,nginx已经安装完成

校验安装

1
2
3
shell复制代码cd /usr/local/nginx
// 检查配置文件
./sbin/nginx -t

启动nginx

1
2
3
4
5
6
7
bash复制代码cd /usr/local/nginx
./sbin/nginx

ps -ef|grep nginx // 检查是否启动成功

./sbin/nginx -s stop // 停止
./sbin/nginx -s reload // 重新启动

关于如何加入开机启动等自行搜索,习惯了在目录下操作,这里就不展开了。

配置nginx正向代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
ini复制代码user  www;
worker_processes 4;


events {
worker_connections 1024;
}

http {
include mime.types;
default_type application/octet-stream;
server_names_hash_bucket_size 128;
client_max_body_size 20m;
client_body_buffer_size 256k;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
sendfile on;
tcp_nopush on;
keepalive_timeout 60;
tcp_nodelay on;
server {
listen 9080;

resolver 114.114.114.114 valid=60s ipv6=off;
resolver_timeout 5s;

proxy_connect;
proxy_connect_connect_timeout 10s;
proxy_connect_read_timeout 10s;
proxy_connect_send_timeout 10s;

location / {
set $forbiden Y;

if ($host = "www.baidu.com" ) {
set $forbiden N;
}

if ( $forbiden = Y){
return 403;
}
proxy_set_header Host $host;
proxy_pass http://$host;
}
}
}

特殊提醒

resolver 114.114.114.114 valid=60s ipv6=off; 这里ipv6一定要关掉,部分网站开启了ipv6的域名解析,目前不支持,会导致访问失败

域名访问白名单

nginx支持简答的逻辑判断,通过host变量获取当前请求的域名,$forbiden进行逻辑判断

客户端设置

基于浏览器界面操作

操作路径设置-高级-打开计算机代理设置,设置你的服务器IP+端口即可。

linux等基于命令行操作

1
2
shell复制代码 export http_proxy=http://$proxy_ip:$proxy_port
export https_proxy=http://$proxy_ip:$proxy_port

浏览器插件

推荐使用SwitchyOmega

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%