Nginx服务器配置ThinkPHP5站点

Nginx服务器配置ThinkPHP5站点,包括像FastAdmin这种使用ThinkPHP5的框架。

在配置上主要有三点:

  1. PHP文件转发
  2. 重写规则
  3. PATHINFO模式的处理

这三点只要有一个处理不好,就会出现问题,比如

  1. PHP文件找不到
  2. PHP文件能找到但是会被下载而不是被执行
  3. 重写的URL,像/index/index/test这样的URL不能被正常解析
  4. 前台URL能正常解析,但后台一登录就提示模块不存在

现在很多PHP开发人员都使用宝塔部署站点,而宝塔把这些问题都给预先处理好了,导致很多人不用宝塔就不会部署,在我看来这不是什么好现象。

下面给出一个示例配置default.conf,可将其置于/etc/nginx/conf.d/目录下。

server {
    listen       80;
    server_name  www.testapp.com;

    access_log  /var/log/nginx/testapp.access.log;

    index  index.php index.html index.htm;

    root   /user/share/nginx/html/public;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /user/share/nginx/html/public;
    }

    # 适用于FastAdmin类的ThinkPHP5框架
    location ~ [^/]\.php(/|$) {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        include        fastcgi_params;
        set $real_script_name $fastcgi_script_name;
        if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
                set $real_script_name $1;
                set $path_info $2;
        }
        fastcgi_param SCRIPT_FILENAME  /user/share/nginx/html/public/$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $real_script_name;
        fastcgi_param PATH_INFO $path_info;
    }

    # 重写规则
    location / {
         if (!-e $request_filename) {
             rewrite  ^(.*)$  /index.php?s=$1  last;
             break;
         }
    }
}

上面的配置有几个注意点:

  1. 站点的根目录设置为public,同时在其下建立一个user.ini文件,使得可以访问上层文件夹,内容如下
open_basedir=/user/share/nginx/html/:/tmp/
  1. 对PHP文件的处理相对nginx的默认配置改动不小,首先是location ~ \.php$ 改成了location ~ [^/]\.php(/|$),就样就可以处理类似/index.php/index/login这样的URL。其次是加入了PATHINFO的配置。

  2. 重写规则放在了PHP规则的下方。

Leave a Comment

豫ICP备19001387号-1