nginx配置PATH_INFO模式

咱們能夠使用PATH_INFO來代替Rewrite來實現僞靜態頁面, 另外很多PHP框架也使用PATH_INFO來做爲路由載體php

在Apache中, 當不加配置的時候, 對於PHP腳本, Accept pathinfo是默認接受的html

PATH_INFO是服務器狀態中的一個參數,經過$_SERVER['PATH_INFO']能夠查看內容nginx

apache下配置以下apache

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*).html$ index.php/$1 [QSA,PT,L]

好比你訪問 http://127.0.0.1/pathinfo/index.html安全

 

可是nginx上有一些$_SERVER變量不支持 好比,$_server['http_x_forwarded_for'] 、$_SERVER['PATH_INFO']服務器

這樣一來對於嚴重依賴PATH_INFO的框架,就很麻煩了app

好比Thinkphp框架

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

給出了這麼一種方案,這也只是折衷而已了socket

nginx中通常的配置爲php-fpm

location ~* \.php$ {
           fastcgi_pass    unix:/dev/shm/php-fpm.socket;
           fastcgi_index   index.php;
           fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
           include        fastcgi.conf;
           include        fastcgi_params;
 }. 

php自己有一個cgi.fix_pathinfo配置選項,不過因爲安全問題已經棄用了

 

看了看網上的資料,nginx中有一個fastcgi_param配置文件用來配置fastcgi_param

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;#腳本文件請求的路徑  
fastcgi_param  QUERY_STRING       $query_string; #請求的參數;如?app=123  
fastcgi_param  REQUEST_METHOD     $request_method; #請求的動做(GET,POST)  
fastcgi_param  CONTENT_TYPE       $content_type; #請求頭中的Content-Type字段  
fastcgi_param  CONTENT_LENGTH     $content_length; #請求頭中的Content-length字段。  
  
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name; #腳本名稱   
fastcgi_param  REQUEST_URI        $request_uri; #請求的地址不帶參數  
fastcgi_param  DOCUMENT_URI       $document_uri; #與$uri相同。   
fastcgi_param  DOCUMENT_ROOT      $document_root; #網站的根目錄。在server配置中root指令中指定的值   
fastcgi_param  SERVER_PROTOCOL    $server_protocol; #請求使用的協議,一般是HTTP/1.0或HTTP/1.1。    
  
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;#cgi 版本  
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;#nginx 版本號,可修改、隱藏  
  
fastcgi_param  REMOTE_ADDR        $remote_addr; #客戶端IP  
fastcgi_param  REMOTE_PORT        $remote_port; #客戶端端口  
fastcgi_param  SERVER_ADDR        $server_addr; #服務器IP地址  
fastcgi_param  SERVER_PORT        $server_port; #服務器端口  
fastcgi_param  SERVER_NAME        $server_name; #服務器名,域名在server配置中指定的server_name  
  
#fastcgi_param  PATH_INFO           $path_info;#可自定義變量  
  
# PHP only, required if PHP was built with --enable-force-cgi-redirect  
#fastcgi_param  REDIRECT_STATUS    200;  

fastcgi_param PHP_VALUE "auto_prepend_file=/data/header.php";

看到沒有fastcgi_param上的參數都是$_SERVER變量的,另外還能夠來配置php.ini

 

全部結合nginx自身的語法就有了

 

新版本的nginx也能夠使用fastcgi_split_path_info指令來設置PATH_INFO,舊的方式再也不推薦使用,在location段添加以下配置

location ~ ^.+.php {
  (...)
  fastcgi_split_path_info ^((?U).+.php)(/?.+)$;
  fastcgi_param SCRIPT_FILENAME /path/to/php$fastcgi_script_name;
  fastcgi_param PATH_INFO $fastcgi_path_info;
  fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
  (...)
}

 

對了,nginx+lua 也能夠配置的

相關文章
相關標籤/搜索