LoginSignup
30
38

More than 5 years have passed since last update.

htaccessで正規表現を使ったリダイレクト

Last updated at Posted at 2016-03-24

サイトの移転や構成を変えた時に、新しいURLへ転送するために使用するリダイレクト。
Redirect(mod_alias)とRewrite(mod_rewrite)があるが、今回はRedirectを使った.htaccessの書き方。
mod_rewriteでも同じことができたり、より複雑な条件でリダイレクトさせることもできる。

基本の形

#普通バージョン
Redirect permanent 移転前パス 移転後パス
#正規表現を使うバージョン
RedirectMatch permanent 移転前パス 移転後パス

正規表現を使ってリダイレクトさせる

使用例①

ディレクトリを分割して転送したい

「西暦+月」でディレクトリを作っていたが…

  • /201601/
  • /201602/
  • /201603/
  • /201701/
  • /201702/
  • /201703/

「西暦」「月」を分けたのでリダイレクトさせたい

  • /2016/
    • /01/
    • /02/
    • /03/
  • /2017/
    • /01/
    • /02/
    • /03/

こんな感じで転送されるようにする

http://foge.com/201601/inu.html
↓転送↓
http://foge.com/2016/01/inu.html

リダイレクトの書き方

.htaccess
#同ドメインの場合
RedirectMatch permanent ^/([0-9]{4})([0-9]{2})/(.*)$ /$1/$2/$3

#ドメインも移転した場合
RedirectMatch permanent ^/([0-9]{4})([0-9]{2})/(.*)$ http://移転先ドメイン/$1/$2/$3

([0-9]{4})…4桁の数字
([0-9]{2})…2桁の数字
(.*)…すべての文字列

$1…ひとつ目のカッコの内容 (※上記の場合は、4桁の数字が入る)
$2…ふたつ目のカッコの内容 (※2桁の数字)
$3…みっつ目のカッコの内容 (※すべての文字列)

使用例②

特定のディレクトリやファイル以外を転送したい

このディレクトリ(ファイル)は転送したくない、というとき。
参考サイト: https://gist.github.com/nagasato/2288987

リダイレクトの書き方

.htaccess
#hogehogeディレクトリ以外転送
RedirectMatch permanent ^/((?!hogehoge).*)$ http://移転先/$1

#/test.html以外転送
RedirectMatch permanent ^/((?!test\.html).*)$ http://移転先/$1

#条件を複数指定する場合
RedirectMatch permanent ^/((?!(hogehoge|fugafuga)).*)$ http://移転先/$1

使用例③

トップページだけを転送したい

http://ほげどっとこむ/
http://ほげどっとこむ/index.html
どちらでアクセスしても、
http://転送先/
に転送する。
ディレクトリ単位でもできる。

index.html(index.php)のありなしを統一したい

いわゆるURL正規化と言われるやつ。

リダイレクトの書き方

.htaccess
#トップページだけ転送・URL正規化
RedirectMatch permanent ^(/|/index\.html)$ http://転送先/

#特定ディレクトリのURL正規化
RedirectMatch permanent ^/gogogo(/|/index\.php)$ http://転送先/gogogo/

使用例④

拡張子を変えたい

例えばHTMLを全部PHPにしたときに。

リダイレクトの書き方

.htaccess
#.htmlを.phpに
RedirectMatch permanent ^(.*)\.html$ 転送先/$1.php

30
38
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
30
38