server {
listen 80;
server_name example.com;
rewrite ^ https://$host$request_uri? permanent;
}
この ^
(キャレット) ってどういう意味なんでしょうか?いつも思考停止でコピペしているので知りませんでした。そこで調べてみました。
rewrite の第 1 パラメータは正規表現で、この正規表現にマッチした URI を第 2 パラメータに置き換えます。^
は行頭を意味し、^
のみの場合はあらゆる文字列にマッチします。つまり、あらゆる URI を置き換えるという意味のようです。
ところで、公式のテックブログの Creating NGINX Rewrite Rules という記事には次のように書かれています。
This is less efficient than the equivalent return directive, because it requires NGINX to process a regular expression, albeit a simple one (the caret [ ^ ], which matches the complete original URL). The corresponding return directive is also easier for a human reader to interpret: return 301 more clearly indicates that NGINX returns code 301 than the rewrite ... permanent notation does.
server {
listen 80;
server_name example.com;
rewrite ^ https://$host$request_uri? permanent;
}
は
server {
listen 80;
server_name example.com;
return 301 https:/$host$request_uri;
}
と書いた方がパフォーマンスがよく、なおかつ「301 redirect を返す」ということが読み取れるので可読性にも優れているということらしいです。なるほど