nginx-1.11.9で確認
例えば、hostsで定義した
http://dev.example.jp/hoge/
を
http://dev-hoge.example.jp/
にプロキシしたい場合、nginxで以下のように設定しますが、
server {
listen 80;
server_name dev.example.jp;
location ~ ^/hoge/(.*)$ {
proxy_pass http://dev-hoge.example.jp/$1?$args;
}
...
}
dev-hoge.example.jpのIPアドレスをhostsで解決していた場合、
でアクセスしても、hosts参照をしてくれず、Not Foundとなってしまいます。
※error.log には以下のように出力されます
2017/03/23 20:19:11 [error] 19306#0: *11 no resolver defined to resolve dev-hoge.example.jp, client: 172.17.0.5, server: dev.example.jp, request: "GET / HTTP/1.1", host: "dev.example.jp"
2017/03/23 20:19:11 [error] 19306#0: *11 open() "/usr/share/nginx/html/50x.html" failed (2: No such file or directory), client: 172.17.0.5, server: dev.example.jp, request: "GET / HTTP/1.1", host: "dev.example.jp"
※ちなみに、rewrite設定の場合は、hosts参照してくれるようで、正しくリダイレクトされます。
rewrite ^/hoge/$ http://dev-hoge.example.jp/ permanent;
解決策
dnsmasqをインストール
dnsmasqは/etc/hostsを参照するDNSサーバーです。
# yum install dnsmasq
# service dnsmasq start
# chkconfig dnsmasq on
dnsmasqはlocalhostの53番ポートで起動します。
$ telnet 127.0.0.1 53
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
/etc/resolv.conf に127.0.0.1を追加し、
nameserver 127.0.0.1
digコマンドで、hostsで定義したホスト名を参照すると、Aレコードとして引くことができます。
$ dig dev-hoge.example.jp
; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.47.rc1.52.amzn1 <<>> dev-hoge.example.jp
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43153
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;dev-hoge.example.jp. IN A
;; ANSWER SECTION:
dev-hoge.example.jp. 0 IN A 172.17.50.11
;; Query time: 6 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Thu Mar 23 22:12:02 2017
;; MSG SIZE rcvd: 57
resolver ディレクティブを追加
proxy_passの直前に、resolverディレクティブを追加し、127.0.0.1を参照するように設定します。
server {
listen 80;
server_name dev.example.jp;
location ~ ^/hoge/(.*)$ {
resolver 127.0.0.1;
proxy_pass http://dev-hoge.example.jp/$1?$args;
}
...
}
dnsmasqとnginxを再起動し、
# service dnsmasq restart
# service nginx restart
でアクセスすると、今度は、Not Foundとならず、hostsで定義した
の内容をプロキシすることができます。