LoginSignup
12
5

More than 3 years have passed since last update.

nginxとphp-fpmの構成でトップページ以外が404になる問題の解決

Posted at

問題点

  • grav と呼ばれる軽量 CMS を利用してサイトを立ち上げたところ、トップページ 例: http://ドメイン/は正常に表示されるが、サブフォルダ 例: http://ドメイン/blog が 404エラーになってしまう問題が発生。
  • 構成: 図1.png
  • それぞれのバージョンは以下
    • nginx 1.14
    • php 7.2

原因

  • nginx の routing 設定で、サブフォルダが指定された場合に、 php-fpm に処理を飛ばせていなかったことが原因。
  • 図2.png

原因のコード

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/html;
    index index.php index.html index.htm;
    server_name _;

    location / {
        try_files $uri $uri/ =404; # <--ここで 404 判定されている
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }
}
  • php-fpm に処理を渡す前に nginx が 404 を返却している、ということから、location /内で 404 に判定されてしまっている、ということになる。

対処

対処方針

  • grav は、/blog とリクエストされると、いったん /index.php が処理を受け取って内部処理を行う流れになっている
  • とにかく php-fpm に処理を渡さないことには話にならないので、処理を渡すこと、そして、処理用のスクリプトは index.php であることを明示させておく。

対処コード

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/html;
    index index.php index.html index.htm;
    server_name ドメイン;

    location / {
        try_files $uri $uri/ @grav;
    }

    location ~ \.php$ {
        try_files $uri $uri/ @grav;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }

    location @grav {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME  /var/www/html/index.php;
        include fastcgi_params;
    }
}

解説

  • location / で 対象のファイルが存在しなかった場合、処理を @grav に渡すように変更
  • location @grav にて、php-fpm を動作させる。その際にパラメータとして SCRIPT_FILENAME で index.php が処理用スクリプトであることを明示しておく。

参考にしたサイト

12
5
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
12
5