VIVEK PANDHARKAR Linux,Uncategorized,Web Server How to Add Custom File Extension for PHP in Apache and Nginx

How to Add Custom File Extension for PHP in Apache and Nginx

by Luke P. Issac on March 16, 2014

Typically you’ll see .php as the extension for PHP files that are served by a web server.

Sometimes you might also have a PHP file that has an extension other than .php, and in those cases, the web server might not be able to serve that file.

For discussion purpose, let us assume that you have written PHP server side coding in a file with “.myext” extension. For some reason, you want to keep the file extension this way for testing purpose, without having to rename it to .php

This tutorial explains how you can allow either your Apache or Nginx to serve this .myext PHP file.

Apache Web Server – Add to mime_module

Open your httpd.conf file, and locate the following lines:

<IfModule mime_module>
AddType ....
AddType ....

On Linux, you will find httpd.conf file under “/etc/apache2/” (or under /usr/local/apache2/conf, if you’ve installed Apache 2 from source).

On Windows, you’ll find “apache/conf” folder on the drive in which you have installed Apache server. If you are using XAMPP, on Windows, you will find it under “c:\xampp\apache\conf” folder.

Since we want to allow .myext, add the following line under the mime_module section of the httpd.conf file

AddType application/x-httpd-php .myext

You can also add your custom extension .myext to default page stack. Find the lines “DirectoryIndex index.php index.htm index.html”, add add the new extension as shown below.

DirectoryIndex index.php index.htm index.html index.myext

After the above change, restart your Apache server.

Apache Web Server – Using .htaccess file

Create a plain text file named “.htaccess” and add the following line to it:

Addhandler application/x-httpd-php .html .php .myext

Place this file in your web root so that this rule applies to the files in that folder.

Nginx Web Server – Add custom extension

Open the /etc/nginx/nginx.conf file and locate the following lines:

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

Edit the first line shown above, and change it to the following to add “.myext” as custom file extension.

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

Restart your Nginx server. You can also use .htaccess with Nginx in the same way as explained for Apache.

After performing any one of the above changes, you should be able to serve both .php and .myext PHP server files.