nginx serve custom index.html

1.7k Views Asked by At

i have the next directory structure for my application:

app
  - nginx
    - n.conf
  - public
    - index.html

and nginx configuration:

 worker_processes  1;

 events {
   worker_connections  1024;
 }

 http {
   default_type  application/octet-stream;

   sendfile        on;

   keepalive_timeout  65;

   server {
     include /etc/nginx/mime.types;
     listen 80 default_server;

     error_log log debug;

     root public/;

     location /bar {
        add_header Content-Type text/plain; 
        return 200 'ok';   
     }

     location ~* ^/foo$ {
        rewrite ^(.*)$ $1/ permanent;
     }

     location ~* ^/foo/$ {
        add_header Cache-Control no-cache;
        index index.html;
     }

  }
}

i run nginx from local (app) folder:

nginx -s reload -c /home/user/app/nginx/n.con

if i open http://127.0.0.1/bar all works fine, i get ok as response but if i open http://127.0.0.1/foo/ then i get 404

in access log

27.0.0.1 - - [29/Aug/2017:22:34:00] "GET /foo/ HTTP/1.1" 404 571 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36"

how to return index.html from this example?

1

There are 1 best solutions below

2
On

Try changing

 location ~* ^/foo/$ {
    add_header Cache-Control no-cache;
    index index.html;
 }

to

 location ~* ^/foo/$ {
    add_header Cache-Control no-cache;
    index index.html;
    try_files /index.html =444;
 }

I have used 444 so you know the error was generated from here