尝试了下 ThinkPHP 框架, 版本为 3.2.3, 测试环境为 Windows 下 Nginx 1.6 + PHP 5.5。本文内容为解决 Nginx 下 ThinkPHP URL 模式中所用到的 PATHINFO 与 REWRITE 模式的配置问题。并在 Mac OS X 10.10 下 Nginx 1.8.0 + PHP 5.6.8 下测试通过。理论同样适用于各版本的 Linux 系统中。
PATHINFO 与 REWRITE 模式在表现上的不同在于浏览器的 URL 地址栏中, 以访问 Home 模块, User 控制器, login 操作为例:
PATHINFO 下的 URL: http://localhost/index.php/Home/User/login
REWRITE 下的 URL: http://localhost/Home/User/login
在这之前, 笔者也到搜索引擎上看了几篇关于 Nginx 配置 PATHINFO 的方法, 感觉有点乱, 乱的原因主要是由于 Nginx 没有给予像 Apache 那样一个参数即可开启 PATHINFO 的良好支持, 因此出现了各种 Nginx 下开启 PATHINFO 的解法。
这里提供的是参阅 Nginx 官方文档并结合实测可用后的 PATHINFO 的方案。去除不必须的注释, Nginx 开启 PATHINFO 的 server 部分配置如下:
server {
listen 80;
server_name localhost;
location / {
root D:/Projects/Demo/thinkphp; # 你的 TP 框架 index.php 所在目录, 记得用 / 分割路径
index index.php index.html index.htm;
}
# ...
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ ^(.+.php)(.*)$ {
root D:/Projects/Demo/thinkphp; # 你的 TP 框架 index.php 所在目录, 记得用 / 分割路径
fastcgi_split_path_info ^(.+.php)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
这种做法的原理是当请求的访问路径中含有 .php 时, 通过正则表达式构造出 PATHINFO, 并设置到 fastcgi 的参数 PATH_INFO 中。
代码中匹配 PATH_INFO 的正则表达式来源于 Nginx 官方文档中的写法。参见: http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_split_path_info
PATHINFO 模式是 ThinkPHP 默认的 URL 模式, 因此不需要修改 ThinkPHP 的默认配置即可使用 http://serverName/index.php/模块/控制器/操作 方式访问。
REWRITE 模式也称 URL重写, 可用于隐藏 PATHINFO 模式路径中的 index.php, 开启 REWRITE 模式的 Nginx 配置为:
server {
listen 80;
server_name localhost;
location / {
root D:/Projects/Demo/thinkphp; # 你的 TP 框架 index.php 所在目录, 记得用 / 分割路径
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?s=$uri; # 核心
}
# ...
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ .php$ {
root D:/Projects/Demo/thinkphp; # 你的 TP 框架 index.php 所在目录, 记得用 / 分割路径
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
配置完成后修改 ThinkPHP 的 URL 模式为 REWRITE, 编辑配置文件 ThinkPHP/Conf/convention.php 中修改 URL_MODEL 参数值为 2 (REWRITE 模式)即可通过 http://serverName/模块/控制器/操作 方式访问。