Nginx Reverse Proxy – How to Add index.html on Incoming HTTP Requests

nginxreverse-proxy

I need to set up nginx as a reverse proxy for my static site hosted on DO spaces (S3 type object storage).

The problem with their s3 is that if i request a path name without any specific file name then it does not give index.html as the default (which we were expecting)

if i request s3.example.com/some/path/ then it gives an error instead of serving index.html in that folder. DO knows about this issue but is not going to resolve it any time soon.

We are stuck because we have spent a lot of time and effort migrating to DO. All our paths are in this format because we are migrating from some other setup. we want s3.example.com/some/path/ to load s3.example.com/some/path/index.html – which is normal web server behavior.

Can nginx help as a reverse proxy?
In any case we would be using a reverse proxy in front of the subdomain and doing a proxy_pass ie example.com/some/path/ would be proxy_pass to s3.example.com/some/path/ – this is using normal proxy_pass

I wanted to know if we could add the index.html while doing the proxy_pass – BUT only for requests that do not have any file name. For those requests that have some file name associated with it like example.com/som/path/image.jpg or some other html or other file then we would not want to add the index.html of course.

The issue is that many a times there is no ending / in the url the url is like
1
example.com/some/path OR like
2
example.com/some/path/

And in some other cases it will be
3
example.com/some/path/ex.html (or jpg or whatever)

In the first case we want to add index.html
In second case /index.html
In 3rd case nothing

How would the config look like in this situation?

Thank you in advance…

Best Answer

You could rewrite every URI that either ends with / or does not contain a . in the last path element, before passing it to the upstream server.

For example:

server {
    ...
    location / {
        ...
        rewrite ^(.*)/$ $1/index.html break;
        rewrite ^(.*/[^./]+)$ $1/index.html break;
        proxy_pass ...;
    }
}

See this document for details.