一止长渊

Nginx反向代理

N 人看过
字数:593字 | 预计阅读时长:2分钟

我们的项目是部署到内网的,其中 nginx 帮我们进行反向代理,当用户访问 doermall.com 的时候,我们可以利用 nginx 将请求转发给商品服务 192.168.2.100:9200 服务
本文只是尝试 nginx 反向代理教学,负载均衡请看**Nginx 负载均衡地反向代理**

cd /mydata/nginx/conf
vi nginx.conf

截屏2021-04-17 23.14.30.png

# 查看默认的访问80端口nginx的server块内容
cd conf.d
cat default.conf
# 内容如下
server {
    listen       80;        # 监听80端口
    server_name  localhost;  # 域名为localhost

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;   # 访问域名下的index,可以路由到index.html静态资源
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;  # 定义错误状态码以及对应的错误页面
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

知道了 server 块的配置信息,接下来我们来实现访问域名 doermall.com 路由到(本机 ip 地址)192.168.2.100:10000 商品服务

1、首先修改本地 host 文件,将域名 doermall.com 路由到我们的虚拟机的 ip 192.168.2.100,这样就会直接路由到虚拟机上的 nginx

sudo vi /etc/hosts
# 添加上
192.168.2.200 doermall.com
# 之后机器重启让路由生效,测试浏览器访问doermall.com:9200能访问到elsasticsearch不

截屏2021-04-17 23.49.12.png

2、修改 nginx server 块,将 doermall.com 转发到本机的 ip:192.168.2.100:10000(因为项目是在本地,而不是在虚拟机上的,所以为本机的 ip 地址)

cd /mydata/nginx/conf/conf.d
cp default.conf doermall.conf
vi doermall.conf
# 修改后重启nginx
docker restart nginx

截屏2021-04-17 23.55.14.png
**
流程:
浏览器访问 doermall.com -> 前往本地 DNS 缓存查找到:doermall.com 对应 192.168.2.200 -> 浏览器发起请求 192.168.2.200,请求头 host 上会携带域名 doermall.com -> 虚拟机 Nginx 获取到来访请求的 host 为 doermall.com -> 根据 server 块将 doermall.com 路由到宿主机 ip : 192.168.2.100:10000 商品服务

本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 (CC BY-NC-ND 4.0) 进行许可。