youforce

2ちゃんねる勢いランキングの中の人が書く技術系(?)ブログ

ApacheからNginxへのリプレイス-その1-(Java+Tocat+MySQL)

NginxのWindowsへのインストール

昨日のエントリーに書いたようにNginxを入れてみました。

まずはローカル開発環境のWindowsマシンへ。
開発機の環境はWindows7(64bit)です。

1.http://nginx.org/en/download.html からWindows版をダウンロード。今回のバージョンはnginx/Windows-1.1.14。
2.適当な場所に解凍。今回はC:\project\nginx-1.1.14へ配置。これだけ。
3.Nginxを起動するにはコマンドプロンプトから以下。(Apacheが起動していると80番ポートがバッティングするので注意)

C:\>cd C:\project\nginx-1.1.14
C:\project\nginx-1.1.14>start nginx

4.停止するにはコマンドプロンプトから以下。

C:\project\nginx-1.1.14>nginx -s stop

5.リロードはこう。

C:\project\nginx-1.1.14>nginx -s reload

6.ヘルプが見れますので一回ぐらい目を通しておきましょう。

C:\project\nginx-1.1.14>nginx -h
nginx version: nginx/1.1.14
Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: NONE)
  -c filename   : set configuration file (default: conf/nginx.conf)
  -g directives : set global directives out of configuration file
動作確認

http://localhost/ へブラウザからアクセスしてWork It!じゃなくて「Welcome to nginx!」と表示されれば確認完了。

Apacheからのリプレイス

VirtualHostとproxy_pass(リバースプロキシ)

さて本題です。
localhost:8080で口を開けて待っているTomcatにプロキシします。
設定ファイルのnginx.confを修正します。
以下を追記。(local.ikioi2ch.netはhostsで127.0.0.1に向けてあります)

    server {
        listen   *:80;
        server_name local.ikioi2ch.net;
        client_max_body_size 5M;
        access_log  logs/host.local.ikioi2ch.net.access.log combined;
        error_log  logs/host.local.ikioi2ch.net.error.log debug;
        location / {
            proxy_pass http://localhost:8080/;
        }
    }

server_nameにVirtualHostのドメインを書いて、locationのproxy_passにプロキシ先のURLを書く感じです。

nginx -s reload でリロードをして http://local.ikioi2ch.net/ へアクセス。
おお!出ました!
めっちゃ簡単です。ここまでの所要時間15分でした。

あとはmod_rewriteを使っているのでNginxでも代替を設定しないといけなかったり、様々なチューニングは必要ですが、それはまた次回以降に書きます。

JavaでのHttpServletRequest#getRequestURL()の取れるURLの違い

ロジックの中でHttpServletRequest#getRequestURL()を結構使っているのですが、返却されるURLが違っていたのでメモします。
まずはApachehttp://www.localhost/へアクセスした場合。

String requestUrl = request.getRequestURL().toString();
System.out.println(requestUrl);

実行結果

http://www.localhost/

次にNginxで同じくhttp://www.localhost/へアクセスした場合。

String requestUrl = request.getRequestURL().toString();
System.out.println(requestUrl);

実行結果

http://localhost:8080/

つまりApacheはリクエストされたURLがそのまま返却されるのに対して、Nginxではプロキシした後のURLが返却されます。
ここはアプリ側の改修が必要かなと思いました。
ひょっとしたら色々間違っているかもなので何かありましたらご指摘いただければと思います。