nginxを実務で使うときに重要になってくるlocationディレクティブについて。
ここでは実際のlocationディレクトリとマッチするURLのパターンを見ていきたいと思います。
Contents
locationディレクティブ
下記の設定は http://website.com/admin/ に適用されます。
1 2 3 4 5 6 |
server{ server_name website.com; location /admin/ { } } |
=がつくパターン
= があると完全一致になります。
1 2 3 4 5 |
server{ server_name website.com; location =/abcd { } } |
マッチ
- http://website.com/abcd
- http://website.com/ABCD(ただしOSによる)
- http://website.com/abcd?qr1=6 (クエリがあっても問題はない)
マッチしない
- http://website.com/abcd/ (スラッシュがあるため完全ではない)
- http://website.com/abcde(末尾に余計な文字があるためダメ)
修飾子無し
先頭部分が一致しているものが対象になります。
1 2 3 4 5 |
server{ server_name website.com; location =/abcd { } } |
マッチ
- http://website.com/abcd
- http://website.com/ABCD(ただしOSによる)
- http://website.com/abcd?qr1=6 (クエリがあっても問題はない)
- http://website.com/abcd/ (スラッシュがあってもよい)
- http://website.com/abcde(末尾に余計な文字があっても途中まで一致しているのでOK)
~(正規表現)
指定された正規表現とマッチするURIが対象となり、大文字小文字の区別がある
1 2 3 4 5 6 |
server{ server_name website.com; location ~ ^/abcd$ { } } |
マッチ
- http://website.com/abcd
- http://website.com/abcd?qr1=6 (クエリは影響を与えない)
マッチしない
- http://website.com/ABCD(大文字小文字区別するためNG)
- http://website.com/abcd/ (末尾のスラッシュがあるため合致しない)
- http://website.com/abcde(余分な文字が入っているので合致しない)
ちなみに下記のように~*となると大文字小文字を区別しなくなる。
1 2 3 4 5 |
server{ server_name website.com; location ~* ^/abcd$ { } } |
^~(一致終了パターン)
修飾子がないときと同様で違いは合致した瞬間に他のパターンを探さない。