LoginSignup
39
42

More than 5 years have passed since last update.

NginxでPC,スマートフォンごとにrootディレクトリを変更する方法

Posted at

ユーザエージェントを判別してPC,スマートフォンそれぞれ専用のrootディレクトリを見るようにする。setディレクティブでスマートフォンかどうかのフラグを定義して最後にフラグを用いて処理を振り分けるのがコツ。この方法はアクセス制御とかでもかなり使える。

set $is_sphone 0;
if ($http_user_agent ~ Android) {
  set $is_sphone 1;
}

if ($http_user_agent ~ iPhone) {
  set $is_sphone 1;
}

if ($http_user_agent ~ iPod) {
  set $is_sphone 1;
}

# iPadも切り替えたい場合
#if ($http_user_agent ~ iPad) {
#   set $is_sphone 1;
#}

location / {
  if ($is_sphone = 1) {
    root /var/www/smart_phone;
  }

  if ($is_sphone != 1) {
    root /var/www/pc;
  }
}
39
42
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
39
42