LoginSignup
10
12

More than 5 years have passed since last update.

nginxでサブパスに複数のWordPressを配置する方法

Posted at

基本的にWordPressは複数のテーマを同時に設定することができない。複数テーマを使用可能にするプラグインは存在するが、本体バージョンによるのか、投稿名でのパーマリンクを使用した場合は指定したテーマが採用されない。
そこで複数のWordPressをサブパスに分けて配置したが、実現するのに苦労したのでみんなに共有しておく。

以下の例では2つのWordPressを次のように配置する。

URL ディレクトリ
http://host/wpone/ /var/www/wponeroot/wpone/
http://host/wptwo/ /var/www/wptworoot/wptwo/

http://host/にはWordPress以外が存在していると仮定して、default.confに以下のようにincludeディレクティブを追記する。
なお、nginxの設定フォルダが/etc/nginxであることを前提としている。

/etc/nginx/conf.d/default.conf
server {
    :
    :

    include conf.d/sub/wpone.conf
    include conf.d/sub/wptwo.conf

    :
    :
}

以下は2つのWordPressのそれぞれの設定だが、aliasディレクティブでWordPressの配置先ディレクトリを直接指定するのではなく、rootディレクティブで指定したディレクトリの下にURLのサブパスと同名のサブディレクトリにWordPressを配置するのがコツである。

/etc/nginx/conf.d/sub/wpone.conf
location /wpone {
    root /var/www/wponeroot;

    access_log /var/log/nginx/wpone.access.log  main;
    error_log /var/log/nginx/wpone.error.log;

    # wordpress パーマリンク設定
    try_files $uri $uri/ /wpone/index.php?q=$uri&$args;

    include conf.d/sub/wordpress-common;
}
/etc/nginx/conf.d/sub/wptwo.conf
location /wptwo {
    root /var/www/wptworoot;

    access_log /var/log/nginx/wptwo.access.log  main;
    error_log /var/log/nginx/wptwo.error.log;

    # wordpress パーマリンク設定
    try_files $uri $uri/ /wptwo/index.php?q=$uri&$args;

    include conf.d/sub/wordpress-common;
}

以下は2つのWordPress向けの共通設定である。
複数のロケーション設定に共通点が多い場合は、1つのファイルにまとめてincludeディレクティブで取り込んだ方がメンテナンス性が高くなる。

/etc/nginx/conf.d/sub/wordpress-common
index index.php;
charset utf-8;

# アクセス拒否設定
location ~* /(wp-config|xmlrpc)\.php {
    deny all;
}

# アクセス制限設定
location ~* /wp-login\.php|/wp-admin/((?!admin-ajax\.php).)*$ {
    index index.php;

    # 外部からのアクセス許可
    allow 87.65.43.21;

    # 自身からのアクセス許可
    allow 12.34.56.78;
    allow 127.0.0.1;

    # 上記以外はアクセス拒否
    deny all;

    include conf.d/sub/fastcgi-for-wordpress;
}

include conf.d/sub/fastcgi-for-wordpress;

同じ階層にあるlocationディレクティブはいずれか1つしか採用されないので、上記のようにアクセス制御を行いたい場合は、アクセス制御対象外のPHPファイルに対するphp-fpm用設定を以下のように別ファイルに定義し、それを上記のように2箇所でincludeディレクティブにより取り込むと良い。

/etc/nginx/conf.d/sub/fastcgi-for-wordpress
# php-fpm用設定
location ~\.php$ {
    fastcgi_split_path_info ^(.+\.php)(.+)$;
    fastcgi_pass phpfpm;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    include fastcgi_params;
}

wpone/hogeにwptwoを配置する方法

ちょっとしたTIPSだが、http://host/wpone/hogeにwptwoを配置したい場合は以下のようにリバースプロキシを設定する。

/etc/nginx/conf.d/sub/wpone.conf
location /wpone {
    location /wpone/hoge/ {
        proxy_pass http://localhost/wptwo/;
    }

    :
    :
}
10
12
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
10
12