0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Apache】そのRewriteCond、評価されません!【mod_rewrite】

Posted at

1. クイズ

サーバ: Apache/2.4.62 (Rocky Linux)の環境で

httpd.confの末尾
RewriteCond (何らかの条件)
RewriteRule ^マッチしないパターン$ /dummy.url

として、このサーバにアクセスしたとき、上記の RewriteCond は評価されるだろうか?

2. 答え

評価されない

対応する RewriteRule がそもそもマッチしない時、 RewriteCond ごと無視される仕様のようだ。

この仕様を明示している公式ドキュメントは見当たらなかったが、次の「実験」にてこの仕様が確認できる。

3. 実験

まず、 httpd.conf を次のようにする。

httpd.conf
RewriteEngine On
RewriteMap append "prg:/usr/bin/php /test.php" apache:apache

RewriteCond ${append:${REQUEST_URI}} ^(.*)$
RewriteRule test_pattern /dummy.url

こうすると、 RewriteCond ${append:${REQUEST_URI}} ^(.*)$ が評価されるたびに、
php プログラム /test.php に対して標準入力として(uri + 改行) が渡されるようになる。

標準入力を受け取る度に、 ファイル /test.txt に追記するようにするには、
/test.php を次のようにすればよい。

/test.php
<?php
while(($line = fgets(STDIN)) !== false){
    file_put_contents("/test.txt", $line, FILE_APPEND);
    echo "OK\n";
    fflush(STDOUT);
}

このように設定して、 Apache を再起動したら、

  1. http://(host)/dummy にアクセスする
  2. http://(host)/test_pattern にアクセスする
  3. /test.txt を閲覧してみる

の手順を実行する。

すると、 /test.txt

/test.txt
/test_pattern

となっているはずだ。

これは、 http://(host)/dummy にアクセスしたときは RewriteCond が評価されなかったが、
http://(host)/test_pattern にアクセスしたときは RewriteCond が評価されたことを意味している。

3. 終わりに

実験により、

httpd.conf
RewriteCond (何らかの条件)
RewriteRule ^マッチしないパターン$ /dummy.url

のとき、 RewriteCond がそもそも評価されないことが分かった。
これは一見些細な仕様に見えるが、
例えば RewriteCond ${recode_access_of:%{REMOTE_ADDR}} ^(.*)$
のように、 RewriteCond でプログラムを動かしている場合に、
意図せぬ挙動になる可能性があるから注意が必要である。

RewriteCond を必ず評価させるには、

httpd.conf
RewriteCond (何らかの条件)
RewriteRule ^ -

のように、 対応する RewriteRule として RewriteRule ^ - を与えるのが確実だ。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?