Nginx 配置 pathinfo [转载] - 全栈笔记

Nginx 配置 pathinfo [转载]

任亦伟 Linux, PHP 2014-03-19 99 次浏览 没有评论

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

01
02
location ~ \.php$ {
03
  root html;
04
  fastcgi_pass 127.0.0.1:9000;
05
  fastcgi_index index.php;
06
 
07
  ##通过设置模拟出pathinfo
08
  set $path_info "";
09
  set $real_script_name $fastcgi_script_name;
10
  if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
11
    set $real_script_name $1;
12
    set $path_info $2;
13
  }
14
  fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
15
  fastcgi_param SCRIPT_NAME $real_script_name;
16
  fastcgi_param PATH_INFO $path_info;
17
 
18
  include fastcgi_params;
19
}
20

要点:

1.~ \.php 后面不能有$ 以便能匹配所有 *.php/* 形式的url  #我建议这里使用~ \.php(/.*)?$

2. 通过设置更改 SCRIPT_FILENAME

我在实际使用张将这段代码融合到了fastcgi_params中。下面是我的nginx配置文件示例:

配置虚拟主机部分,支持pathinfo的nginx代码如下:

01
02
## 在nginx.conf的server部分:
03
server {
04
  listen 8080;
05
  server_name localhost;
06
 
07
  location ~ \.php {
08
    include fastcgi.conf;
09
  }
10
}

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

fastcgi.conf 代码如下:

01
02
fastcgi_pass 127.0.0.1:9000;
03
##fastcgi_index index.php;
04
 
05
set $path_info "";
06
set $real_script_name $fastcgi_script_name;
07
if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
08
  set $real_script_name $1;
09
  set $path_info $2;
10
}
11
fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
12
fastcgi_param SCRIPT_NAME $real_script_name;
13
fastcgi_param PATH_INFO $path_info;
14
## 以上是支持pathinfo的重点部分
15
 
16
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
17
fastcgi_param SERVER_SOFTWARE nginx;
18
 
19
fastcgi_param QUERY_STRING $query_string;
20
fastcgi_param REQUEST_METHOD $request_method;
21
fastcgi_param CONTENT_TYPE $content_type;
22
fastcgi_param CONTENT_LENGTH $content_length;
23
 
24
#fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
25
#fastcgi_param SCRIPT_NAME $fastcgi_script_name; 这两行是需要注释掉的。请注意
26
fastcgi_param REQUEST_URI $request_uri;
27
fastcgi_param DOCUMENT_URI $document_uri;
28
fastcgi_param DOCUMENT_ROOT $document_root;
29
fastcgi_param SERVER_PROTOCOL $server_protocol;
30
 
31
fastcgi_param REMOTE_ADDR $remote_addr;
32
fastcgi_param REMOTE_PORT $remote_port;
33
fastcgi_param SERVER_ADDR $server_addr;
34
fastcgi_param SERVER_PORT $server_port;
35
fastcgi_param SERVER_NAME $server_name;
36
 
37
# PHP only, required if PHP was built with --enable-force-cgi-redirect
38
#fastcgi_param REDIRECT_STATUS 200;
39

转载自:http://linuxguest.blog.51cto.com/195664/694319/

发表评论

回顶部