Nginx configuration for index.php with fallback to index.html and serving static files

I have a configuration that works for simple index.php and index.html files in such a way that when I request localhost/ firstly index.php is served and if not preset then index.html is served.

server {
    listen 0.0.0.0:80;

    root /usr/share/nginx/html/public;

    location / {
        index index.php index.html; #works with index.php index.html
    }

    location ~ .php$ {

        include fastcgi_params;
        fastcgi_split_path_info ^(.+.php)(/.*)$;

        fastcgi_pass fpm:9000;
        fastcgi_index index.php;

        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    }
}

but if index.php is a Symfony app and the requested uri is not localhost/ but localhost/some/route

I get 404 Not Found instead of controller response.
Therefore I modified:

location / {
    index index.php index.html; #works with index.php index.html
}

to:

location / {
    try_files $uri /index.php$is_args$args; # works with Symfony
}

that made Symfony php app working as expected but I’ve lost fallback to index.html for localhost/ in case tere was no index.php in /usr/share/nginx/html/public

in case there is no /usr/share/nginx/html/public/index.php I get

Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0
Fatal error: Unknown: Failed opening required '/usr/share/nginx/html/public/index.php' (include_path='.:/usr/local/lib/php') in Unknown on line 0

instead of index.html like when using index index.php index.html; that did not work with symfony index.php for other locations than document root (localhost/)

index.php may be basic php but also a front controller web app that needs to deal with routes like localhost/test/route

How to create Nginx configuration so server will fallback to index.html if no index.php.

for example request_uri => served file:

localhost/ => /usr/share/nginx/html/public/index.php
localhost/ => /usr/share/nginx/html/public/index.html
404

localhost/route => /usr/share/nginx/html/public/index.php?_route=route
localhost/route => /usr/share/nginx/html/public/route/index.html
404

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *