Nginx の location ブロックのパターン化

簡単そうに見えたのだが思い通りにいかない.

優先順位というか, 処理順序というか. ここらの話.

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 
}

Nginx location priority - Stack Overflow

なので公式 wiki/recipe を見ながら少し整理.

PHP FastCGI Example | NGINX

Codeigniter | NGINX

Drupal | NGINX

osCommerce | NGINX

WordPress | NGINX

公式にて書式はこう.

Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }

Module ngx_http_core_module

複数のlocationブロックがある場合, リクエストのURL内該当文字列に対して優先順位の順番にマッチを確認していき, 最初にマッチしたロケーション設定(処理)ひとつが反映される.

1.「=」完全一致
2.「^~」前方検索 (マッチ文字列の長い順)
3.「~」正規表現 (記述順)
4.「~*」正規表現 (記述順・大小文字を考慮しない)
5.「(なし)」前方検索 (マッチ文字列の長い順)

これに加えて, それぞれの設定(処理)自体の優先順位を考慮しておかないと, 「アクセス拒否したつもりが丸出し」や「PHPスクリプトのダウンロード公開」などとなってしまう.

1. 特殊ファイルのログ制御
2. ディレクトリ単位のアクセス拒否
3. ファイル単位のアクセス拒否
4. PHPファイルの実行 (PHP-FPM)
5. 静的ファイルのキャッシュ期限の設定
6. フロントコントローラへのリクエスト付け替え

これら2つの優先順位を考慮にいれながら書かれている公式wiki/recipeの設定は, ある程度おおまかにパターン化できる.

1.「=」特殊ファイルのログ制御
2. 「^~」ディレクトリ単位のアクセス拒否
3.「~」ファイル単位のアクセス拒否
4.「~」PHPファイルの設定・実行 (PHP-FPM)
5.「~*」静的ファイルのキャッシュ期限の設定
6.「なし」フロントコントローラへのリクエスト付け替え

頻出しそうなのを順序を守って箇条書きに.

# 1. specific files 
location = /favicon.ico {
  log_not_found off;
  access_log off;
}

location = /robots.txt {
  allow all;
  log_not_found off;
  access_log off;
}

# 2. deny directories
location ^~ /conf/ {
  return 403;
}

# 3. deny files
location ~ (^|/)\. {
  return 403;
}

location ~ \.(txt|log)$ {
  allow 192.168.0.0/16;
  deny all;
}

# 4. php scripts
location ~ [^/]\.php(/|$) {
  fastcgi_split_path_info ^(.+?\.php)(/.*)$;
  if (!-f $document_root$fastcgi_script_name) {
    return 404;
  }
  fastcgi_pass unix:/var/run/php5-fpm.sock;
  fastcgi_index index.php;
  include fastcgi_params;
}

# 5. static content files
location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
  expires max;
}

# 6. others(internal rewrite)
location / {
   try_files $uri $uri/ index.php;
}

実際はこれらに加えてさらに, 内部/外部での リライト/リダイレクトなどを記述して location 設定を複数またいでいくことになると, 大量に記述された apache mod_rewrite 設定のように直感的に設定できなくなっていくので locationブロックに関してはテンプレ化しておくのがいいように思う.

そもそもは「if」や「locationを使った入れ子」で混乱したので.

nginxのlocation設定について、優先順位の基本と意外な罠

If Is Evil | NGINX

if ($request_uri = /) { 
  set $test  A; 
} 
  
if ($host ~* teambox.com) { 
  set $test  "${test}B"; 
} 
  
if ($http_cookie !~* "auth_token") { 
  set $test  "${test}C"; 
} 
    
if ($test = ABC) { 
  proxy_pass http://teambox-cms.heroku.com; 
  break; 
} 

nginx hack for multiple conditions

手をつける前に, ある程度の歴史や経緯を分かっておく必要があったかな.

Nginx Configuration Primer

まあいいか.

みんなも reload したらチェックしてみよう.

$ curl -L http://yourhost.com/ -o /dev/null \
     -w '%{http_code} %{content_type} %{size_download} %{url_effective}\n' \
     -s

200 text/html; charset=UTF-8 1334 http://yourhost.com/

Mac OSX El Capitan のターミナルに表示される "[" (角カッコ) は何?

これ.

h6yLA

どこかの設定ファイルに間違えて混入させたのかと思って放置していましたが.

ついに 消そうと思って調べていたら便利な OS X 10.11 - El Capitan の機能「mark」というものらしいです.

Marks_and_Edit

Command + ↑
Command + ↓

で移動できます.

Navigate_and_Edit

コマンドの出力結果が多い時にすぐに実行したコマンドの行に戻ることができます.

また, そのコマンドと出力結果を

Shift + Command + ↑
Shift + Command + ↓

でまとめて選択することもできます.

大量な出力結果のコピー&ペーストなどに便利ですね.

けど, まあ OFF にしておこうかな, とくに理由はないけど.

terminal - Why is there a left bracket before my bash prompt? - Ask Different


Related Categories :  NewbiePreference


Android Studio 使えるエディタのテーマを「Color Themes」

IDEのエディタのテーマ集があります.

Color_Themes

Color_Themes 2

Color_Themes

Color Themes

ダウンロードしてインポートするだけ.

How to install a theme?

Select «File» → «Import Setting» from the main menu and follow the instructions. After the IDE restarted go to the Preferences, expand «Editor» → «Colors and fonts» tab and choose the installed theme.

IntelliJ IDEA に使えるということで AndroidStudio でも使えます.

Which IDEs are supported?

Themes on this site support fully all family of JetBrains' IDEs: IntelliJ IDEA, PhpStorm, PyCharm, RubyMine, WebStorm and AppCode.

y-a-r-g/color-themes


Android で よくある正規表現を使えるやつ

そもそもは Linkify のWEBリンクがなんだかな, と思い.

device-2011-08-23-153643

使えそうなよくある正規表現がいくつか用意されていたのですな.

public static final Pattern WEB_URL = Pattern.compile(
    "((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
  + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
  + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?"
  + "(?:" + DOMAIN_NAME + ")"
  + "(?:\\:\\d{1,5})?)"
  + "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~"
  + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"
  + "(?:\\b|$)");
public static final Pattern PHONE
  = Pattern.compile(                
      "(\\+[0-9]+[\\- \\.]*)?"      
    + "(\\([0-9]+\\)[\\- \\.]*)?"   
    + "([0-9][0-9\\- \\.]+[0-9])"); 
public static final Pattern EMAIL_ADDRESS
  = Pattern.compile(
    "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
    "\\@" +
    "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
    "(" +
        "\\." +
        "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
     ")+"
  );

platform_frameworks_base/Patterns.java

すぐにそのまま使おう.


if (Patterns.WEB_URL.matcher(text).find()) {
  // do something
}

「厳格なのか?」でフィルターをつける場合.

// A match filter that only accepts odd numbers.
MatchFilter oddFilter = new MatchFilter() {
    public final boolean acceptMatch(CharSequence s, int start, int end) {
        int n = Character.digit(s.charAt(end-1), 10);
        return (n & 1) == 1;
    }
};

// Match all digits in the pattern but restrict links to only odd
// numbers using the filter.
Pattern pattern = Pattern.compile("[0-9]+");
Linkify.addLinks(text, pattern, "http://...", oddFilter, null);

Android Text Links Using Linkify


Retrofit 2.0-beta で ログを吐かせる

Retrofit

Okhttp 2.6.0+ では HTTPリクエスト/レスポンスのログ出力が可能なのだが,

New Logging Interceptor. The logging-interceptor subproject offers simple request and response logging. It may be configured to log headers and bodies for debugging. It requires this Maven dependency:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(Level.BASIC);
client.networkInterceptors().add(logging);

okhttp/CHANGELOG.md at master · square/okhttp

残念なことに retrofit 2.0.0-beta2 での同梱は 2.5.0 .

<!-- Dependencies -->
<android.version>4.1.1.4</android.version>
<android.platform>16</android.platform>
<okhttp.version>2.5.0</okhttp.version>
<animal.sniffer.version>1.14</animal.sniffer.version>

retrofit/pom.xml at master · square/retrofit

なので logging-interceptor 2.6.0 で.

    <dependency>
      <groupId>com.squareup.okhttp</groupId>
      <artifactId>okhttp</artifactId>
      <version>${project.version}</version>
    </dependency>

okhttp/okhttp-logging-interceptor at master · square/okhttp

compile 'com.squareup.okhttp:logging-interceptor:2.6.0' 
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();  
logging.setLevel(Level.BASIC);
OkHttpClient client = new OkHttpClient();  
httpClient.interceptors().add(logging);
Retrofit retrofit = new Retrofit.Builder()  
   .baseUrl(API_BASE_URL)
   .addConverterFactory(GsonConverterFactory.create())
   .client(httpClient)
   .build();

出力.

...
11:33:04.547 17090-17108 D/OkHttp: <-- HTTP/1.1 200 OK (469ms, 259-byte body)
11:33:04.550 17090-17296 D/OkHttp: --> GET /v5/item/1072964 HTTP/1.1
11:33:04.563 17090-17263 D/OkHttp: <-- HTTP/1.1 200 OK (250ms, 244-byte body)
11:33:04.566 17090-17108 D/OkHttp: --> GET /v5/item/1073510 HTTP/1.1
11:33:04.606 17090-17265 D/OkHttp: <-- HTTP/1.1 200 OK (252ms, 228-byte body)
11:33:04.609 17090-17263 D/OkHttp: --> GET /v5/item/1072585 HTTP/1.1
11:33:04.794 17090-17296 D/OkHttp: <-- HTTP/1.1 200 OK (244ms, 183-byte body)
11:33:04.796 17090-17265 D/OkHttp: --> GET /v5/item/1073275 HTTP/1.1

stable で対応するのかな.