nginx反向代理内外网跳转

现状

一个域名(www.abc.com),指向了公司的外网IP(59.108.xx.xx),

公司的外网IP(59.108.xx.xx),映射到一台内网服务器37(172.16.2.37),以下简称37服务器。

另一台内网服务器38是资源服务器(172.16.2.38),上传了很多的图片,以下简称38服务器。


其中,

37服务器是外网访问我们服务器的唯一入口,其中配置了nginx,跳转到多个服务器的应用。

38服务器,8081端口就是访问图片的应用端口。

希望:

通过外网ip和域名地址,可以访问资源服务器上的图片


实现步骤:

1、配置nginx.conf

#cat /etc/nginx/nginx.conf

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include conf.d/*.conf;
}

这里为了nginx.conf文件结构清晰,将所有的跳转配置到conf.d文件夹的不同的配置文件中。


2、配置nginx_9091_38_static.conf

# cat nginx_9091_38_static.conf 
server {
        listen       9091;
        server_name  127.0.0.1 172.16.2.37 59.108.xx.xx www.abc.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
#            root   html;
#            index  index.html index.htm;
            proxy_set_header Host $host:9091;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://172.16.2.38:8081/;
        }
}

这里仅列出图片服务器的配置文件,

9091是外网访问端口,

59.108.xx.xx www.abc.com是外网访问的ip和域名

http://172.16.2.38:8081 是图片服务器的内网访问地址,也是nginx将9091跳转到的地址


3、重启nginx

nginx -s reload

可以查看/var/log/nginx/下的access.log和error.log文件,查看访问记录和出错记录


4、防火墙开启9091端口

#vi /etc/sysconfig/iptables

-A IN_public_allow -p tcp -m tcp --dport 9091 -m conntrack --ctstate NEW -j ACCEPT

#service iptables restart

5、验证

确保38服务器在8081端口启动了应用,并且开启了8081防火墙。

本地电脑用内网地址验证

http://172.16.2.37:9091/static/1525844569268.jpg


由于本地电脑无法访问外网,所以用手机流量访问以下地址

http://59.108.xx.xx:9091/static/1525844569268.jpg

http://www.abc.com:9091/static/1525844569268.jpg


总结:

本方案是对同一个域名用不同的端口号跳转。

也可以针对不同的应用,创建不同的二级域名,用不同的二级域名跳转,比如img.abc.com,api.abc.com,cms.abc.com。这样就可以不带端口号访问内网服务器的资源了(此时默认端口号为80)。


  • 3
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值