1

I am trying to run php within html on an nginx server. What happens is that the php code within the html just gets printed, not executed. I can run php stanadalone scripts fine. but not ones within html. I have spent hours on this now.

Heres my sites-available/default file:

server {
listen 80 default_server;
listen [::]:80 default_server;

root /var/www/html;

# Add index.php to the list if you are using PHP 
index index.html index.htm index.nginx-debian.html index.php;

server_name _;

location / { 
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ =404;
    }  
}

I think I need to add a location html directive here, but I am unsure how to write it. I have tried several versions but they always give me errors. Anybody know how to proceed from here?

1
  • You need a PHP processor to process PHP, not pure HTML. You'd need to pass this off to the PHP backend on-system in order for it to properly parse PHP, and that needs additional configuration to properly pass it off. (instead of try_files you'd get a fastcgi_pass directive to a PHP-FPM process instead, but that would mean PHP processes all requests instead of nginx, and that's "problematic") Sep 18, 2018 at 17:02

1 Answer 1

2

Usually when you code a site in PHP you give all of your pages a .php extension. This is because you want PHP to parse the page and perform the various script functions you have defined.

By default, when you place PHP in a .html document your webserver doesn't know to send that file to PHP to be parsed. If you want to change the default function of the webserver and have .html files parsed by PHP (it can't determine when one page has it and the next doesn't) you would need to direct the webserver to do so.

This previous question had a similar problem but they were having issues getting PHP extensions to parse. In your case you should be able to take this and replace the .php$ with .html. I'm guessing you already have a config setting for PHP, you just need to add in a section for HTML now.

I wouldn't personally do this though. I would change the file extension for my pages to be .php so that you can easily tell what should be processed and what should be plain HTML. Additionally, if you set .HTML to be processed by PHP by default you may inadvertently allow users to upload other HTML pages with malicious script to be executed by PHP.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .