LoginSignup
1
0

More than 3 years have passed since last update.

nginx の rewrite で古いドメインを新しいドメインに移行する

Last updated at Posted at 2020-06-04

サイトを運用していて、途中からドメインを変更したい場合があります。nginx の rewrite を使うと簡単に移行が出来ます。

rewrite によるドメインの移行

http://old.example.com/index.html -> http://new.example.com/index.html

という様に飛ばしたい場合:

server {
    listen       80;
    server_name  old.example.com;

    rewrite ^ $scheme://new.example.com$request_uri permanent;
}

と設定します。ここで $request_uri はドメインより後ろの文字列で、ドメインだけを書き換えて同じページに飛ばすことが出来ます。単にトップページに飛ばすのではなく、対応するページに飛ばすことが出来ます。

rewrite ^ $scheme://new.example.com$request_uri permanent;
# or
rewrite ^(.*)$ $scheme://new.example.com$1 permanent;

上記の二つは、意味的には等価になりますが、前者の方が正規表現を使わない分、パフォーマンスが良くなります。

rewrite による www の削除

nginx の rewrite は結構便利で数行書くだけで、色々なことが出来ます。例えば、アドレスに www が要らないなと思うなら、この様に書くことで、www を取り除くことが出来ます:

server {
    listen       80;
    server_name  www.example.com;

    rewrite ^ $scheme://example.com$request_uri permanent;
}

rewrite による https の強制

以下のように、https を強制するのにも使えます:

server {
    listen       80;
    server_name  example.com;

    rewrite ^ https://$host$request_uri permanent;
}

参考

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