Edited at

Nginxのリダイレクト設定のメモ

More than 1 year has passed since last update.

個人的なメモなので注意

この辺あれば大体カバーできるかと

# 302の場合

location ^~ /hoge/foo.html {
rewrite ^(.*)$ http://example.com/hoge/foo.html redirect;
}

# 301の場合
location ^~ /foo/bar.html {
rewrite ^(.*)$ http://example.com/foo/ permanent;
}

# ホスト名等引き継ぎ
location ^~ /hoge {
proxy_set_header Host $host;
proxy_set_header X-Proto $http_x_forwarded_proto;
proxy_pass http://127.0.0.1$request_uri;
}

# 特定のクエリの場合だけ転送
location ^~ /hoge/foo.php {
if ($args ~ "(.*)&?hogehoge=01&foobar=1") {
set $args $1$2;
rewrite ^(.*)$ http://example.com/hoge/foo.aspx?hogehoge=foobar permanent;
}

if ($args ~ "(.*)&?hogehoge=01&hoge=2") {
set $args $1$2;
rewrite ^(.*)$ http://example.com/hoge/foo.aspx?hogehoge=hoge permanent;
}
}

# 特定のパスを転送
location ~* ^/hoge/(.*)/info.html {
rewrite /([^/]*)/(.*) http:/example.com/$2 redirect;
}

# HTTPSでのアクセス時だけ転送(ELB経由とか)
location ^~ / {
if ($http_x_forwarded_proto = "https") {
rewrite ^(.*)$ https://example.com$request_uri redirect;
break;
}
}

# 特定のVirtualHostで/あり無しの判断をしたい
# 明示的に分けておく
# 例 :
# sample.com/hoge/foo/bar => example.com/hoge/foo/bar
# sample.com/hoge/foo/bar/ => example.com/hoge/foo/bar
location ^~ /hoge/foo/ {
if ($request_uri ~ "(.+)/$") {
rewrite ^(.+)/$ http://example.com$1 permanent;
}
if ($request_uri ~ "(.*)"){
rewrite ^(.*)$ http://example.com$1 permanent;
}
}