當前訪客身份:游客 [ 登錄 | 加入程式開發 討論區 ]
當前訪客身份:未登入或非會員
alumi alumi
131231

How to hide .php extension in your urls with Nginx

發表於(2014-07-12 09:47:20)  閱讀(475) | 評論(0 0人收藏此文章,
摘要 How to hide .php extension in your urls with Nginx

Looking for clean urls (/hello instead of /hello.php)?

Here's how to set it up:

Step 1

Create a notfound.php script and place it in your root web server folder
 

 
// Set this for easier access 
$url substr($REQUEST_URI,1); 

// Strip parameters 
if (($pos strpos($url,"?"))>0

    
$url_parameters substr($url$pos+1); 
    
$url substr($url0$pos); 

$url trim(strtolower($url)); 

// Strip prefix and suffix '/' 
if ($url[0]=='/'$url substr($url,1); 
if (
strlen($url)>1
if (
$url[strlen($url)-1]=='/'$url substr($url0strlen($url)-1); 

// If url starts with .. it's a hack attempt 
if (Strcasecmp(substr($url,0,2),"..")==0

  
$url str_replace("..","",$url); 


// If we have a php script with this name 
if (file_exists($url.".php")) 

  
// Set PHP_SELF and REQUEST_URI to point to the real script 
  
$_SERVER['PHP_SELF'] = $PHP_SELF $_SERVER['REQUEST_URI'] = $REQUEST_URI ="/".$url
  if (!empty(
$url_parameters)) $_SERVER['REQUEST_URI'] = $REQUEST_URI .="?".$url_parameters

  
// Load real php script 
  
require($DOCUMENT_ROOT."/$url.php"); 
  return; 
}


Step 2

Update your Nginx nginx.conf file, rewriting all urls where the file is not found, to notfound.php
 


    location 
    { 
      if (-
d $request_filename
      { 
        break; 
      } 
      if (!-
f $request_filename
      { 
        
rewrite ^(.*)$ /notfound.php?$1 last
        break; 
      } 
    }


Note: This is different than doing an error_document 404 redirect. With a 404 redirect, HTTP_POST data is not preserved.

評論0