LoginSignup
19
18

More than 5 years have passed since last update.

Nginxのlocationを使ってDocumentRootの外に配置されたアプリを動作させる方法

Last updated at Posted at 2016-10-05
  • Nginxの設定でなかなかハマってしまったので、最終的に動いた設定をメモしておきます。

やりたいこと

  • 例えば、www.your-domain.com/subdirでアクセスしたときに、DocumentRootの外にあるWordPressやフレームワークアプリを実行させたい。

    /path/to/your/document/root/for
        ├─ www.your-domain.com
        │ ├── _root_                < アクセスURL:www.your-domain.com
        │ └── subdir                < アクセスURL:www.your-domain.com/subdir
    

前提

  • Nginx + PHP-FPM + MariaDBで構成されてたLEMP-APサーバ。(あ、MariaDBはどうでもいいや。)
  • subdirにおいたアプリは、FrameWorkやらWordPressやらのお作法に従って、サブディレクトリ運用する設定にしておく。

設定

  • /etc/nginx/conf.d/xxxxxxx.confを編集

    /etc/nginx/conf.d/xxxxxxx.conf
    server  {
        listen 80;
        server_name www.your-domain.com;
    
        location / {
            root /path/to/your/document/root/for/www.your-domain.com/_root_;
            index index.php index.html;
            if (-f $request_filename) {
                expires 30d;
                break;
            }
            if (!-e $request_filename) {
                rewrite ^(.*)$ /index.php?q=$1 last;
            }
            location ~ .php$ {
                fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
                fastcgi_index index.php;
                include /etc/nginx/fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            }
        }
    
        location /subdir {
            alias /path/to/your/document/root/for/www.your-domain.com/subdir;
            index index.php index.html;
            if (-f $request_filename) {
                expires 30d;
                break;
            }
            if (!-e $request_filename) {
                rewrite ^(.*)$ /subdir/index.php?q=$1 last;
            }
    
            location ~ ^/subdir/.+\.php$ {
                fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
                fastcgi_split_path_info ^/subdir(.+\.php)(.*)$;
                include /etc/nginx/fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            }
        }
    }
    
  • PHP-FPM & Nginx 再起動

    console
    /etc/rc.d/init.d/php-fpm restart
    /etc/rc.d/init.d/nginx restart
    
  • 上記の設定でやりたいことは実現できた。

19
18
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
19
18