7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nginx の rewrite ディレクティブの ^ って何?

Last updated at Posted at 2017-07-24
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 を返す」ということが読み取れるので可読性にも優れているということらしいです。なるほど :innocent:

7
4
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?