nginx服务自定义index.html

时间:2017-08-29 19:40:15

标签: nginx nginx-location

我有我的应用程序的下一个目录结构:

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

和nginx配置:

 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;
     }

  }
}

我从本地(app)文件夹运行nginx:

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

如果我打开http://127.0.0.1/bar一切正常,我会得到ok作为回复 但是,如果我打开http://127.0.0.1/foo/,那么我会得到404

访问日志中的

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"

如何从此示例中返回index.html

1 个答案:

答案 0 :(得分:0)

尝试更改

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

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

我使用了444,因此您知道错误是从这里生成的