TRY AND ERROR

気になったこと、勉強したこと、その他雑記など色々メモしていきます。。Sometimes these posts will be written in English.,

.htaccessのリダイレクトなどでつかう正規表現の%とか$とか

.htaccessで以下の様にサブドメを継承し、かつ最初のディレクトリをカットするということがしたくて色々やってハマったのでメモ。

http://xxx.from.com/yyy/zzz...

http://xxx.to.com/zzz...
にリダイレクトしたい。。。


結論、こんな感じになりました。

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/yyy.*$
RewriteCond %{HTTP_HOST} ^(.*).from.com$
RewriteRule ^yyy/(.*)$ http://%1.to.com/$1 [R=301,L]


RewriteCondのキャプチャパターンをRewriteRuleで使う場合、%Nで指定する。
mod_rewrite - Apache HTTP Server Version 2.4

RewriteRule backreferences: These are backreferences of the form $N (0 <= N <= 9). $1 to $9 provide access to the grouped parts (in parentheses) of the pattern, from the RewriteRule which is subject to the current set of RewriteCond conditions. $0 provides access to the whole string matched by that pattern.
RewriteCond backreferences: These are backreferences of the form %N (0 <= N <= 9). %1 to %9 provide access to the grouped parts (again, in parentheses) of the pattern, from the last matched RewriteCond in the current set of conditions. %0 provides access to the whole string matched by that pattern.<<



なお、RewriteCondの順番を逆にすると%1に値が引き継がれないのですが、これは複数のRewriteCondの中で上から順に下に継承されるからだそう。

www.sitepoint.com


こちらのサイトが参考になります!
.htaccess で RewriteCond の後方参照 ← Neo Inspiration