LoginSignup
257

More than 5 years have passed since last update.

Nginxによるリバースプロキシの設定方法

Last updated at Posted at 2016-06-08

Nginxをリバースプロキシとして利用するための方法と個人用メモ

プロキシ設定

Nginxをリバースプロキシとして利用するためには、/etc/nginx/conf.d に設定ファイルを配置すればよい
ファイル名は {ConfigName}.conf
今回は server.conf としてファイルを配置した

以下のように server.conf を用意して Nginx を再起動する

server.conf
server{
    server_name    example.com;

    proxy_set_header    Host    $host;
    proxy_set_header    X-Real-IP    $remote_addr;
    proxy_set_header    X-Forwarded-Host       $host;
    proxy_set_header    X-Forwarded-Server    $host;
    proxy_set_header    X-Forwarded-For    $proxy_add_x_forwarded_for;

    location /example/ {
        proxy_pass    http://localhost:8080/app/;
    }

    location /example2/ {
        proxy_pass    http://example2.com/example/;
    }
}

proxy_set_header の記述により、転送先にアクセス元のIPやホスト情報を通知する
location は複数記述可能
クッキーの書き換えも可能で、書き方は proxy_cookie_path /abc/ /edf/; のようになる

rewriteディレクティブ

rewriteディレクティブを記述することで apache の mod_rewriteと同様のことができる

書き方は rewrite regexp replacement option となっている
具体例は以下

rewrite /reg/(.*) /replace/$1 last;

option には以下のどれかを指定可能

オプション 説明
last rewriteルールが適用されるとURLを上書きして処理を終了
break URLを上書きして処理を続行
redirect HTTP 302 temporary redirect を返す
permanent HTTP 301 redirect を返す

参考サイト

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
257