如何使用nginx从子目录中提供单页应用程序?

时间:2017-12-01 17:29:13

标签: angular nginx

我正在尝试配置nginx以从应用程序唯一的子路径提供Angular应用程序。我已经修改了应用程序以使用fish的基本href,我可以正确地提供根页面及其资源。

我无法在子路线上重新加载页面。我得到了404。

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
  worker_connections  1024;
}


http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;

  log_format  main  '$request_uri --- $remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

  access_log  /var/log/nginx/access.log  main;

  sendfile        on;
  keepalive_timeout  65;


    upstream docker-backend-stream {
      server fish-api:80;
    }

    server {
      listen 80;
      autoindex off;

      location / {
            rewrite ^ http://www.google.com redirect;
      }

      location /fish {
        alias /app;
        index index.html;
        try_files $uri $uri/ /index.html;
      }

      location /fish/api {
            proxy_pass http://docker-backend-stream;
            auth_basic          off;
            client_max_body_size  0;
        }
    }
}

为什么http://localhost:80/fish/foo的GET请求没有被提供给index.html?它收到404 Not Found。

日志:

as-web_1       | 2017/12/01 18:16:14 [error] 8#8: *2 open() "/etc/nginx/html/index.html" failed (2: No such file or directory), client: 172.24.0.1, server: , request: "GET /fish/foo HTTP/1.1", host: "localhost"
as-web_1       | /fish/foo --- 172.24.0.1 - - [01/Dec/2017:18:16:14 +0000] "GET /fish/foo HTTP/1.1" 404 571 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" "-"

如上所示 - location指令未匹配,因此nginx正在/ etc / nginx / html的默认根位置查找资产。

1 个答案:

答案 0 :(得分:1)

似乎有一个历史nginx错误阻止root和别名正确地抓住location指令。

http://trac.nginx.org/nginx/ticket/97

我的工作使用条件检查,然后是正则表达式&重写:

  location /fish {
    alias /app;
    if (!-e $request_filename) {
      rewrite ^[^.]*$ /fish/index.html last;
    }
  }

注意:这肯定可以改进以检查文件扩展名