nginx反向代理无法使用hosts

背景

  1. 多个域名通过nginx反向代理给frps,然后转发给frpc做内网穿透。
  2. 由于frps的https内网穿透模式不会取host(http head),只会取URI上的地址,所以无法使用proxy_pass到127.0.0.1
  3. 使用proxy_pass到sub1.xxx.com ,然后修改/etc/hosts ,让其指向127.0.0.1 ,但是nginx的proxy_pass不使用/etc/hosts解析。

解决方案

需要搭建一个自己的dns解析服务器,用来解析这个域名

安装dnsmasq

apt-get install dnsmasq

安装过程中提示失败,原因是53端口被systemd-resolved占用了,但systemd-resolved不会解析/etc/hosts并让他在nginx的proxy_pass中生效 ,不知道为什么。

所以就需要停止systemd-resolved对53端口的占用了

先查看53端口占用情况,确认是否是systemd-resolved占用的。

lsof -i :53

ubuntu@dujin:~$ sudo lsof -i :53
COMMAND   PID            USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
systemd-r 591 systemd-resolve   12u  IPv4  19824      0t0  UDP 127.0.0.53:domain 
systemd-r 591 systemd-resolve   13u  IPv4  19825      0t0  TCP 127.0.0.53:domain (LISTEN)

确认后编辑文件vim /etc/systemd/resolved.conf

[Resolve]
DNS=8.8.8.8
#FallbackDNS=
#Domains=
#LLMNR=no
#MulticastDNS=no
#DNSSEC=no
#DNSOverTLS=no
#Cache=yes
DNSStubListener=no
#ReadEtcHosts=yes

只需要把DNS和DNSStubListener放开,并设置DNSStubListener为NO

接着将/run/systemd/resolve/resolv.conf作为/etc/resolv.conf目标地址链接起来。

sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf

最后 sudo reboot 重启服务器即可

现在可以继续安装了,继续启动dnsmasq。

systemctl start dnsmasq.service

设置为开机启动

systemctl enable dnsmasq.service

配置dnsmasq

创建配置文件,这个文件配置上游dns

vi /etc/resolv.dnsmasq

nameserver 114.114.114.114
nameserver 8.8.8.8

接着配置服务的配置文件,需要放开addn-hosts、和resolv-file

vi /etc/dnsmasq.conf

# If you don't want dnsmasq to read /etc/hosts, uncomment the
# following line.
#no-hosts
# or if you want it to read another file, as well as /etc/hosts, use
# this. 找到这里配置下面 addn-hosts
addn-hosts=/etc/dnsmasqhosts

# Change this line if you want dns to get its upstream servers from
# somewhere other that /etc/resolv.conf  这里配置resolv.dnsmasq文件
resolv-file=/etc/resolv.dnsmasq

在配置自定义的内网域名解析

vi /etc/dnsmasqhosts

127.0.0.1 xxx.shellingford.cn

最后重启服务即可

systemctl restart dnsmasq.service

配置nginx反向代理

一定要使用resolver指向127.0.0.1 ,如此才能使用本机的域名解析功能

location ^~ / {
    proxy_pass https://$host:8101; 
    proxy_set_header Host $host:$server_port; 
    proxy_set_header X-Real-IP $remote_addr; 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    proxy_set_header REMOTE-HOST $remote_addr; 
    proxy_set_header Upgrade $http_upgrade; 
    proxy_set_header Connection "upgrade"; 
    proxy_set_header X-Forwarded-Proto $scheme; 
    proxy_http_version 1.1; 
    add_header X-Cache $upstream_cache_status; 
    add_header Strict-Transport-Security "max-age=31536000"; 
    add_header Cache-Control no-cache; 
    resolver 127.0.0.1;
    proxy_ssl_server_name on;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}