Question

How do I get Nginx to recognize index.php and not throw a 403 and not serve index.php as a 404?

If I drop an index.html file into my web root it is recognized fine. An index.php file is, however, not served and a 403 forbidden is instead served. Unless you explicitly request it in the URI and then it will be served.

But then it is also served as the 404 apparently??? 🤯🤷🏻‍♂️…where any nonsense address or string that would otherwise serve a 404 is serving index.php just fine.

Go figure. As in please, …go help me figure this out. Such a strange matrix of behaviors.

I am using DO’s Nginx configurator, but to be fair have had the same or similar problems on many past Nginx setups. Why setting up sane defaults for index.html and index.php fallbacks is so tedious and invites so much different and often contradictory advice will remain a mystery to me. I’ve seen so many versions now of what a location try_files {} directive “should” look like, I am not sure what to believe.

Any help or hints appreciated.

https://www.digitalocean.com/community/tools/nginx#?0.domain=monogram.dk&0.php=false&0.python&0.index=index.html&0.fallback_html&0.access_log_domain&0.error_log_domain

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hello,

The following Nginx server block usually works well for me:

server {
        listen 80;
        root /var/www/html;
        index index.php index.html index.htm index.nginx-debian.html;
        server_name example.com;

        location / {
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        }

        location ~ /\.ht {
                deny all;
        }
}

You first need to add the index.php file in the index list and then also have a ~ \.php$ location, so that Nginx would know how to handle the .php requests.

Hope that this helps! Regards, Bobby