By default, PHP code is executed only in files with a .php extension. If you try to add PHP code inside an .html file, it will usually be ignored and sent to the browser as plain text.
However, there are scenarios, such as integrating small dynamic features into static HTML pages, where you may want your .html files to process PHP code.
This guide explains how to configure your server so that PHP can run inside .html files.
Why Would You Want This?
- Add dynamic elements (like contact forms, date/time, or includes) without renaming files to .php.
- Preserve existing URLs that end in .html while adding PHP functionality.
- Integrate PHP into legacy websites without restructuring the file system.
Methods to Parse PHP in HTML Files
1. Using .htaccess (Apache Web Server)
If you are running Apache and have access to .htaccess, you can tell the server to treat .html files as PHP.
Add this to your .htaccess file in the website root:
AddType application/x-httpd-php .html .htm
Or, if your hosting uses PHP as an Apache module:
AddHandler application/x-httpd-php .html .htm
Note: This will make Apache parse all .html and .htm files through PHP, which may slightly impact performance if you have many static pages.
2. Editing Apache Configuration (httpd.conf)
If you have access to the main Apache configuration file (httpd.conf), you can add:
AddType application/x-httpd-php .html .htm
After editing, restart Apache:
# sudo service apache2 restart
3. Using Nginx with PHP-FPM
For Nginx, update your server block to include .html in the PHP processing location:
location ~ \.php$|\.html$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
Then restart Nginx:
# sudo service nginx restart
4. Renaming Files (Simplest Approach)
If you control the code and the URLs are not a concern, simply rename:
index.html → index.php
This avoids server configuration changes and is the recommended option for new projects.
Security Considerations
- Performance Impact – Parsing PHP in every HTML file can slow down static sites.
- Potential Vulnerabilities – If a malicious user can upload .html files, they could execute PHP code.
- Best Practice – Only enable this for specific directories or files that need PHP execution.
Conclusion:
Parsing PHP in .html files is possible by updating your web server configuration—most commonly via .htaccess in Apache or the Nginx server block. While this can help integrate dynamic features into existing static pages, it should be used cautiously due to performance and security implications. Whenever possible, consider renaming files to .php instead, as it’s the cleaner and safer approach.
