Nginx下支持ThinkPHP的Pathinfo和URl Rewrite模式

时间:2023-03-09 00:32:33
Nginx下支持ThinkPHP的Pathinfo和URl Rewrite模式

下面介绍如何使Nginx支持ThinkPHP的Pathinfo和URL Rewrite模式。

1、ThinkPHP给出了ThinkPHP的官方解决方案,如下:

打开Nginx的配置文件 /etc/nginx/nginx.cof 一般是在这个路径,根据你的安装路径可能有所变化。如果你配置了vhost,而且只需要你这一个vhost支持pathinfo的话,可以直接打开你的 vhost的配置文件。找到类似如下代码(不同版本的nginx可能稍有不同,但是相差不会很远):

    location ~ .php
{
#原有代码 #定义变量 $path_info ,用于存放pathinfo信息
set $path_info "";
#定义变量 $real_script_name,用于存放真实地址
set $real_script_name $fastcgi_script_name;
#如果地址与引号内的正则表达式匹配
if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
#将文件地址赋值给变量 $real_script_name
set $real_script_name $1;
#将文件地址后的参数赋值给变量 $path_info
set $path_info $2;
}
#配置fastcgi的一些参数
fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
fastcgi_param SCRIPT_NAME $real_script_name;
fastcgi_param PATH_INFO $path_info;
}

这样,nginx服务器就可以支持pathinfo了。但是如果要支持ThinkPHP的URL_MODE设置为2的模式,还需要配置rewrite规则。找到access_log语句,在其上方加上以下语句:

    #如果请求既不是一个文件,也不是一个目录,则执行一下重写规则
if (!-e $request_filename)
{
#地址作为将参数rewrite到index.php上。
rewrite ^/(.*)$ /index.php/$1;
#若是子目录则使用下面这句,将subdir改成目录名称即可。
#rewrite ^/subdir/(.*)$ /subdir/index.php/$1;
}

以上方法虽然是ThinkPHP官方给出的,想必也是经过验证的,但悲催的是对我并不起作用。

2、我的解决方案

我是在sites(vhost)下配置的,在/etc/nginx/sites-available/目录下。当然你也可以直接在/etc/nginx/nginx.conf里配置。
在localhost / {} 配置中加如下代码:

#如果请求既不是一个文件,也不是一个目录,则执行一下重写规则
if (!-e $request_filename)
{
#地址作为将参数rewrite到index.php上。
rewrite ^/(.*)$ /index.php/$1;
#若是子目录则使用下面这句,将subdir改成目录名称即可。
#rewrite ^/subdir/(.*)$ /subdir/index.php/$1;
}

完整代码如下:

location / {
root /var/www;
# First attempt to serve request as file, then
# as directory, then fall back to index.html
try_files $uri $uri/ /index.html;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
if (!-e $request_filename)
{
rewrite ^/PHPParser/(.*)$ /PHPParser/index.php?s=$1 last;
break;
}
}

然后在localhost ~ \.php{}配置栏目中添加如下两行:

fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;

完整配置如下

 location ~ \.php$ {
root /var/www;
try_files $uri = 404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
#fastcgi_pass 127.0.0.1:9000;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
# # With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}