0
0

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 1 year has passed since last update.

【Apache】クエリパラメータの値を基にリダイレクトを行う

Last updated at Posted at 2023-12-17

事のはじまり

わたし「MediaWikiを別サーバーに移行するよ」
わたし「使っていたドメインはレンタルサーバー会社から貸し出されているサブドメインだったから独自ドメインにするよ」

(中略)

わたし「やっと移行できたよ…あとはしばらく旧サーバーでリダイレクトするだけ…」
???「パス構成も変わったけどどうするんですか」
わたし「あっ」

新旧のパス比較

旧サーバーでのパス
/wiki/index.php?title=<ページタイトル>
新サーバーでのパス
/<ページタイトル>

というわけで、クエリパラメータに指定しているページタイトルを抜き出してパスに入れこまないといけません。
移行ついでにURLをすっきりさせようとかするからこうなる。

というわけで正解の.htaccess

.htaccess
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/wiki/index.php$
RewriteCond %{QUERY_STRING} (?:^|&)title=([^&]+)
RewriteRule ^(.*)$ https://<新ドメイン>/%1? [R=301,L,NE]

Rewriteの条件は、下記の2つです。

  • リクエストURIが /wiki/index.php である
  • クエリパラメータに title があり、1文字以上指定されている

Rewriteの内容は下記の通りです。

  • 新ドメインの /<titleパラメータ> に301リダイレクトする
  • 置換後URLの末尾に ? をつけることで、元々あったクエリパラメータをすべて削除
  • オプションで NE (No Escape) をつけることでtitleパラメータを再エスケープしない

おわりに

これ、もう二度と書きたくないので記録としてここに残します。(などと)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?