合同会社BUSTERWORKS

合同会社BUSTERWORKS

ブログBLOG

Nginx リバースプロキシ入門

2019.3.1
IT

Ruby on RailsやNode.jsなどで動作するWebアプリケーションは、単体ではhttpに対応していません。そのためNginxをリバースプロキシとしてhttpに対応されることが多いです。今回はその方法について解説します。なお、本手順はCentOS7を対象としています

 Nginxのインストール

リバースプロキシとして使用するNginxのインストールをおこないます。

\r\n# yum -y install epel-release\r\n# yum -y install --enablerepo=epel nginx\r\n# systemctl start nginx\r\n# systemctl enable nginx\r\n

 

 Firewalldの設定

以下のコマンドを入力し、Firewalldの設定を変更してhttp/httpでのアクセスを許可します。

\r\n# firewall-cmd --add-service=http --permanent\r\n# firewall-cmd --add-service=http --permanent\r\n# firewall-cmd --add-port=3000/tcp --permanent\r\n# firewall-cmd --reload\r\n

 

certbotのインストール、SSL/TLS証明書の取得

\r\nLet’s Encryptのクライアントであるcertbotをインストールし、SSL/TLS証明書の取得をおこないます。[fqdn]のところは、サーバのホスト名を入力します(事前にDNSの設定がなされている必要があります)\r\n\r\n

\r\n# curl http://dl.eff.org/certbot-auto -o /usr/bin/certbot-auto\r\n# chmod 700 /usr/bin/certbot-auto\r\n# certbot-auto certonly --webroot -w /usr/share/nginx/html -d [fqdn] --email [email-address]\r\n

\r\n\r\n

nginx.confの編集

\r\n/etc/nginx/nginx.confを開き、以下の通り編集します。\r\n\r\n

\r\n# vi /etc/nginx/nginx.conf\r\n

\r\n\r\n

\r\nserver {\r\nlisten 443 ssl;\r\nserver_name [fqdn];\r\nssl_certificate /etc/letsencrypt/live/[fqdn]/cert.pem;\r\nssl_certificate_key /etc/letsencrypt/live/[fqdn]/privkey.pem;\r\nroot /usr/share/nginx/html;\r\naccess_log /var/log/nginx/ssl-access.log main;\r\n\r\nlocation / {\r\nproxy_set_header X-Real-IP $remote_addr;\r\nindex index.html index.htm;\r\nproxy_set_header X-Forwarded-Proto $scheme;\r\nproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\r\nproxy_set_header Host $http_host;\r\nproxy_redirect off;\r\nproxy_pass http://127.0.0.1:3000;\r\n}\r\n\r\n}\r\n

\r\n\r\nNginxをrestartします。httpでアクセスして3000番ポートで公開しているサイトにリダイレクトされれば成功しています。\r\n

\r\n# systemctl restart nginx\r\n

\r\n

TOPへ戻る