欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

nginx配置支持php的pathinfo模式配置方法

程序员文章站 2022-05-12 18:32:26
nginx模式不支持pathinfo模式,类似info.php/hello形式的url会被提示找不到页面。下面的通过正则找出实际文件路径和pathinfo部分的方法,让ng...

nginx模式不支持pathinfo模式,类似info.php/hello形式的url会被提示找不到页面。下面的通过正则找出实际文件路径和pathinfo部分的方法,让nginx支持pathinfo。

location ~ \.php$ {
root      html;
fastcgi_pass  127.0.0.1:9000;
fastcgi_index index.php;
 
##通过设置模拟出pathinfo
set $path_info “”;
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 $document_root$real_script_name;
fastcgi_param script_name $real_script_name;
fastcgi_param path_info $path_info;
 
include    fastcgi_params;
}

要点:

1.~ \.php 后面不能有$  以便能匹配所有 *.php/* 形式的url
2. 通过设置更改 script_filename

我在实际使用张将这段代码融合到了fastcgi_params中。下面是我的nginx配置文件示例:
配置虚拟主机部分,支持pathinfo的nginx代码如下:

## 在nginx.conf的server部分:

server {
listen    8080;
server_name localhost;
 
location ~ \.php {
include    fastcgi.conf;
}
}

##要点: \.php 后面没有$,以便匹配所有 *.php/* 形式
##重点代码见 fastcgi.conf 开头部分

fastcgi.conf 代码如下:

fastcgi_pass  127.0.0.1:9000;
##fastcgi_index index.php;

set $path_info "";
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 $document_root$real_script_name;
fastcgi_param script_name $real_script_name;
fastcgi_param path_info $path_info;
## 以上是支持pathinfo的重点部分

fastcgi_param gateway_interface cgi/1.1;
fastcgi_param server_software  nginx;

fastcgi_param query_string    $query_string;
fastcgi_param request_method   $request_method;
fastcgi_param content_type    $content_type;
fastcgi_param content_length   $content_length;

#fastcgi_param script_filename  $document_root$fastcgi_script_name;
#fastcgi_param script_name    $fastcgi_script_name;
fastcgi_param request_uri    $request_uri;
fastcgi_param document_uri    $document_uri;
fastcgi_param document_root   $document_root;
fastcgi_param server_protocol  $server_protocol;

fastcgi_param remote_addr    $remote_addr;
fastcgi_param remote_port    $remote_port;
fastcgi_param server_addr    $server_addr;
fastcgi_param server_port    $server_port;
fastcgi_param server_name    $server_name;

# php only, required if php was built with --enable-force-cgi-redirect
#fastcgi_param redirect_status  200;

自己的配置:

server
{
listen    80;
server_name www.touchopenid.com;
index index.html index.htm index.php;
root /data0/htdocs/openid;
 
location ~ \.php($|/) {
set $script   $uri;
set $path_info "";
if ($uri ~ "^(.+\.php)(/.+)") {
set $script   $1;
set $path_info $2;
}
fastcgi_pass  127.0.0.1:9000;
include    fastcgi_params;
fastcgi_param path_info        $path_info;
fastcgi_param script_filename     $document_root$script;
fastcgi_param script_name       $script;
}