5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nginx で AND 条件を記述した話

5
Last updated at Posted at 2015-12-05

プロキシ設定を書いている中で必要になってきたため、試したものをメモ。

ググったりしてみると Nginx の if では、論理 AND を使用する場合に、変数に文字列を保持して連結していき、最終的にこの変数を評価することで、論理 AND を実現している例が多数見つかった。

ただ、この書きかたは、お世辞にもきれいとはいえない。
少なくとも自分には我慢ならなかった。

そこで もう少しどうにか、きれいにならないかと試してみたのが以下。

/etc/nginx/sites-enabled/default
server {

        ...

        location / {
                # 変数の初期値に、真の値を設定しておく
                set $spring_xd_json 1;

                # Accept ヘッダに "application/json" が含まれない場合、
                # 偽の値で上書き
                if ($http_accept !~* application/json) {
                        set $spring_xd_json 0;
                }

                # Referer ヘッダが "/spring-xd/admin-ui/" で終わらない場合、
                # 偽の値で上書き
                if ($http_referer !~* /spring-xd/admin-ui/$) {
                        set $spring_xd_json 0;
                }

                # Accept ヘッダに "application/json" が含まれ、
                # かつ、Referer ヘッダが "/spring-xd/admin-ui/" で終わる場合、
                # 真の値のまま
                if ($spring_xd_json = 1) {
                        proxy_pass http://localhost:9393$request_uri;
                }
        }
}

記述例は Spring XD 向けのもの。

見ればわかるとおり、はじめに最終評価用の変数を用意しておき、初期値に最終的な if に入るための値を設定しておく。
その後 必要な分だけ、否定条件を設定した if を記述し、いずれかに引っかかってしまったら、最終的な if には入らない値で上書きされる、というもの。

文字列連結で、論理 AND を実現するよりも、幾分かきれいなものにできた。

5
3
0

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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?