Run a PHP script with a .html extension

Sometimes it is desirable to configure your web server so that files that end in .html are treated as PHP scripts, which usually end in .php. There are different reasons you might want to do this. One is that by using the .html file extension, you make it less obvious to a possible cracker that your site is using PHP, thus possibly slowing him down in an attack. Some people also believe that pages ending in .html rank higher in some search engines than pages ending in .php. Furthermore, there are those who think that it is inelegant to give clues as to the technology behind a page, which may change in the future.

Configuring Apache to treat .html files as PHP scripts is actually very easy - a one liner that can be made in one of two places. The line itself is:

AddType application/x-httpd-php .php .html

The line above makes use of the AddType Apache configuration directive, which, as described in the Apache manual, "maps the given filename extensions onto the specified content type". The line above tells Apache that files with .html filename extensions should be treated as PHP scripts. Consequently, the page will be processed by the PHP interpreter when it ends in .html. This does not affect preexisting filename extensions mappings, such as PHP, files ending in which will continue to be handed to the PHP interpreter.

If you add this line to your main Apache configuration file (often called something like httpd.conf), it will affect your whole site. You can also limit its effect to a particular virtual host or directory within your main configuration file. If you prefer to apply the rule on a per directory basis outside of the main configuration file, you can add it to .htaccess files in the relevant directories. This latter method is sometimes the only available option if you are using shared hosting, but is also convenient because it doesn't require that you restart the server for the directive to take effect. It does, however, incur a performance hit as Apache has to read the contents of the file on each request for a page in the same directory (and sub-directories).

To test the set up, add the line above with the AddType directive to your main server configuration file or to a .htaccess file and upload a file called test.html with the following contents:

<php print "Hello, world!"; ?>

Type in the URL of the file and check what appears. If you see "Hello, world!", then the set up has been successful. If it has been unsuccessful, the page will simply be blank.

If you are using shared hosting to try out the AddType directive in a .htaccess file, make sure that this is supported by your host. Also, some hosts may take a certain amount of time to "notice" a new .htaccess file, so the effects may not be immediate.