Sep
24
2010

Run PHP Under A Different File Extension in NGINX

Be it for SEO or Security reasons, sometimes you need to run php as an extension other than .php in NGINX.

Share
Email

You can take care of the URL one of two ways.

  • Rewrites – In which with NGINX you’re probably already having to play in the nginx.conf file for.
  • Tell your server configuration to flat out run a different file or exentsion as php and dont worry about covering it up with a URL rewrite. This is great for single file access and the mod that will be explained further here.

Why? Security and SEO

  • Security - Confusing a would be hacker on the server side scripting languages you’re using definitely isn’t a sure shot security method. But in combination with other methods its a welcomed improvement. I’ve also had cases where a piece of JavaScript needs to be given to other webmasters to place on their site. Instead of having the SRC field link back to a very obvious php file on your site, it looks MUCH better for them to see something like this: http://domain.com/some.button. Where “some.button” is the file that sits in the root directory and runs as PHP.
  • SEO - Some of older sites were created with urls such as .html. If the site is small enough it would be best to 301 these to a new url in which was generated by a CMS. Sometimes thats tedious work or for other reasons isnt the easiest option. So if not you can run php and access your mysql database from a .html page without risking you traffic to that URL.

How To Modify nginx.conf

Somewhere in your /etc/nginx/nginx.conf file you probably have the following line:

location ~ .*\.php$ {
	root   /var/www/html/www.domain.com;
	if (!-f $request_filename) {
		rewrite ^/(.*)$ /index.php?q=$1;
		break;
	}
	include        fastcgi_params;
	#root           html;
	fastcgi_pass   127.0.0.1:9000;
	fastcgi_intercept_errors off;
	fastcgi_index  index.php;
	fastcgi_param  SCRIPT_FILENAME  /var/www/html/www.domain.com$fastcgi_script$
}

This is an incredibly easy change. If you want to use the extension “.button” which would allow you to run PHP on files such as topsite.button or yoursite.button then change your first line as follows:

location ~ .*\.php|.*\.button$ {

Maybe you also want a very specific file to run as PHP too (one without an extension). Given a file named “tpsreport” you can add the following:

location ~ .*\.php|.*\.button|tpsreport$ {

Like in Apache, remember to reload/restart NGNIX after you’re done making changes.

Respond: Leave A Comment | Trackback URL

Entrupeners, Subscribe for the lastest tools, tips, and tutorials.


2 Responses to Run PHP Under A Different File Extension in NGINX

  1. You should not use -f for file existence in Nginx conf. The right way is using try_files directive. This issue has been covered in common pitfalls guide on Nginx wiki

Leave a Reply

Custom Theme by Rob Malon | Content & Design © 2010 - RobMalon.Com - Chicago, Illinois