Help us understand the problem. What is going on with this article?

nginxの$arg_がリダイレクトに便利

More than 3 years have passed since last update.

何のこったい

ngx_http_core_module:var_arg_に書いてある通り。

argument name in the request line

URLのパラメータ(クエリストリング)の値を取ることができる。

知らなかった。
めっちゃ便利。

例えば

http://some.domain.local/path?param1=hogehoge&?param2=fugafuga
みたいなURIの場合、
$arg_param1 には hogehoge$arg_param2 には fugafuga という文字列が入っている。

どういうときに役立つのか

パラメータからパスに変換してリダイレクトをかけるなどが可能になる。
(旧システムから新システムへの移行に役に立った)

http://old.domain/path_to_redirect?parent=[param 1]&child=[param 2]http://new.domain/new_path/[param 1]/[param 2] にリダイレクトを書けたい

location /path_to_redirect {
    rewrite .* http://new.domain/new_path/$arg_parent/$arg_child? permanent;
}

※ rewriteで?をつけると、元のパラメータが引き継がれない

実際に動かしてみると

$ http "http://old.domain/path_to_redirect?parent=bob&child=alice"
HTTP/1.1 301 Moved Permanently
Connection: keep-alive
Content-Length: 185
Content-Type: text/html
Location: http://new.domain/new_path/bob/alice
Server: nginx/1.10.1

まとめ

クエリストリングをベースに何か処理するときに、めんどくさい正規表現を書く必要がない!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした