Call us Toll-Free:
1-800-218-1525
Live ChatEmail us

 Sponsors

How to hide .php extension in your urls with Nginx

Adrian Singer, 11-04-2010
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($url, 0, $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($url, 0, strlen($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.

Josh Fraser, 11-04-2010
Isn't there something similar to .htaccess for Nginx? I'd expect you should be able to do something more like this:

RewriteRule ^([^.?]+)$ %{REQUEST_URI}.php [L]

drew, 08-15-2011
Thanks buddy
josh fraser
yours is much better Thanks

Amer, 09-06-2011
I could not find nginx.conf file !!

Rajeev Jha, 10-20-2011
I just do not understand it. if all you are doing is redirect to a pHP script that uploads the file then you may as well do that with a rewrite rule in Nginx. why do all this drama? Also, checking file existence with -f in Nginx 0.7.6 onwards qualifies as "stupid things you should not do", use try_files instead.

andria, 11-26-2014
Thnks, i have try it but not run.
bbm pin share girl www.facecutes.com
Enjoyed this post?

Subscribe Now to receive new posts via Email as soon as they come out.

 Comments
Post your comments












Note: No link spamming! If your message contains link/s, it will NOT be published on the site before manually approved by one of our moderators.



About Us  |  Contact us  |  Privacy Policy  |  Terms & Conditions