Score:1

Nginx get / from /index.php without "directory index is forbidden" elsewhere

us flag

I need / to be shown like /index.php.

Right now I have

index index.php;
if ( $request_uri = /index.php ) { return 301 /; }
location / { try_files $uri $uri/ =404; }

And everything works fine but there are some errors like

directory index of "/home/.../public_html/tmp/" is forbidden

which I want to remove. The problem here is $uri/ in try_files $uri $uri/ =404;

https://stackoverflow.com/questions/19285355/nginx-403-error-directory-index-of-folder-is-forbidden/38046124#38046124

Ubuntu + Nginx: directory index of "/var/www/app/my-app/" is forbidden

But if I change this to try_files $uri =404; or try_files $uri /index.html index.php =404; then "/" just stops working and shows 404

Why does removing $uri/ prevent showing index.php if I have index index.php;?

How can I set that / should check index.php and if there is no index.php then just shows 404 without throwing "is forbidden" error?

Richard Smith avatar
jp flag
Does your website have more than one `index.php` file?
us flag
Maybe there are several but I only care about root `/index.php`. It all works now but with `directory index of "..." is forbidden` when someone hit page that is not here because of `$uri/`.
Score:2
jp flag

The $uri/ term in a try_files statement has two distinct purposes.

If the URI does not end with a /, but does reference a directory, Nginx will generate a 301 redirection to append a /.

If the URI ends with a / and references a directory, the Index functionality will be invoked, which can either result in an internal redirection to an index file, or a 403 response if the index file is not found.

One solution to suppressing the 403 response without affecting too many other things is to handle URIs which end with a / differently.

For example:

location ~ /$ { 
    if (-f ${request_filename}index.php) {
        rewrite ^(.*)/$ $1/index.php last;
    }
    return 404;
}

The above will test for the existence of index.php within the directory, and return 404 if it does not exist.

Score:0
us flag

The following approach might work:

location = /index.php {
    return 301 /;
}

location / {
    try_files $uri $uri/ /index.php =404;
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.