Carpe Diem

備忘録

Nginx でリバースプロキシを設定

概要

1024番以下のポートを使用する場合、root権限がいるためnodeやrailsでは直接80番や443番を使えません。
そんなときにポートフォワードするためのリバースプロキシをnginxで構築します。

環境

  • Ubuntu 14.04
  • Nginx 1.4.6
  • Node 0.12.3

Nginxの設定

最低限の設定にするため初期設定のバックアップをとっておきます。

$ cd /etc/nginx/
$ sudo mv nginx.conf nginx.conf.org

nginx.confを以下のように設定します。

user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
        worker_connections 1024;
}

http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_disable "msie6";

        include /etc/nginx/conf.d/*.conf;
}

includeでバーチャルホストの設定を読み込むので、conf.d以下に以下の設定を新規作成します。
リクエストヘッダの設定などは最低限しか入れてないので、必要に応じて設定してください。
/etc/nginx/conf.d/node.conf

server {
        listen 80;
        listen [::]:80;
        server_name 0.0.0.0;

        location / {
                proxy_set_header Host $http_host;
                proxy_pass http://localhost:3000;
        }
}

今回はNodeサーバをたてるので、ポートは3000番です。

Nodeサーバの用意

$ npm install -g express-generator
$ express test
$ cd test
$ npm install 
$ ./bin/www

動作確認

curlでアクセスしてみましょう

$ curl localhost
<!DOCTYPE html><html><head><title>Express</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>Express</h1><p>Welcome to Express</p></body></html>

80番アクセスしてますが、Nodeサーバのレスポンスが返ってきました。
お疲れ様でした。

ソース