Nginx not serving php files but downloading them

I can serve a custom 404 page if no file exists, however, when I try to also remove .html and .php ext from URLS where a file does exist the 404 stops working and vice versa. I am trying to do both. Sever a specific 404.php file and also when a file exists then remove the .php ext from the URL.

Here is config

server {
    listen 80;
    listen [::]:80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}
server {
    # Port to listen on, can also be set in IP:PORT format
    listen  80;
    listen [::]:80;

    server_name example.com; 

    error_page 404 @not_found;
    location @not_found {
        try_files /page-404.html @fallback;
    }
    location @fallback {
        root /opt/bitnami/nginx/html;
        try_files /page-404.html =404;
    }

}

Does anyone know how to do both?

I wanted to update this with the solution. To be clear, this is for NGINX blueprints installed in AWS Lightsail. The default install of NGINX does not have all of the same files as you would expect from many of the questions/answers you will find online. Notice the fastcgi lines. This is not handed to you and is not easily available online to find the lines. You may need to modify your server blocks to include listen 443 ssl if you have a cert installed. Obviously change example.com to your website address. Hope it helps!

server {
    listen 80;
    listen [::]:80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    # Port to listen on, can also be set in IP:PORT format
    listen  80;
    listen [::]:80;

    server_name example.com www.example.com;

    error_page 404 /custom-404.php;

    index index.html index.php;
    location / {
        if ($request_uri ~ ^/(.*)\.html$) {  return 302 /$1;  }
        try_files $uri $uri/ $uri.html $uri.php?$args;
    }
    location ~ \.php$ {
        if ($request_uri ~ ^/([^?]*)\.php($|\?)) {  return 302 /$1?$args;  }
        try_files $uri =404;
        fastcgi_read_timeout 300;
        fastcgi_pass   unix:/opt/bitnami/php/var/run/www.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $request_filename;
        include        fastcgi_params;
    }

    location = /custom-404 {
        try_files $uri =404;
        internal;
    }
}
2 Likes