nginx.conf中的try_files不起作用

我正在使用angular度为2的应用程序,nginx和docker。 每当我用/ site重新加载一个页面时,它会给我一个404.我的服务器块看起来像这样:

server { listen 0.0.0.0:80; listen [::]:80; root /var/www/project/html; index index.html; server_name project.com; location / { try_files $uri $uri/ /index.html; }} 

我已经尝试了很多,并已经看到了所有其他的stackoverflow问题,并尝试了所有的可能性。 但没有任何工作。 有人可以帮忙吗?

更新:整个nginx.conf:

 user nginx; worker_processes auto; 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 '$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; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } 

sites-enabled / default:

  server { listen 0.0.0.0:80; listen [::]:80; root /var/www/project/html; index index.html; server_name project.com; location / { try_files $uri $uri/ /index.html; }} 

和Dockerfile:

 FROM nginx COPY ./docker/sites-enabled /etc/nginx/sites-enabled COPY ./docker/nginx.conf /etc/nginx/nginx.conf COPY ./dist /var/www/project/html COPY ./dist /usr/share/nginx/html EXPOSE 80 

在你的nginx.conf中,你从两个位置加载其他configuration:

 include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; 

第二个加载您的sites.enabled/defaultconfiguration与服务器名称project.com

但是,第一个默认情况下加载默认configurationdefault.conf ,它是nginx docker镜像的一部分。 该configuration看起来类似于

 server { listen 80; server_name localhost; .... location / { root /usr/share/nginx/html; index index.html index.htm; } .... } 

因此,如果您尝试使用localhost访问您的站点,则您的sites-enabled/default不会被使用(因为您指定了server_name project.com并且与localhost不匹配)。 相反,请求运行在default.conf因为server_name是localhost

而在default.conf的位置部分是:

 location / { root /usr/share/nginx/html; index index.html index.htm; } 

这意味着,如果你只是去localhostindex.html服务,一切按预期工作。 但只要你尝试访问localhost/something ,Nginx正试图find文件/目录/usr/share/nginx/html/something不存在的/usr/share/nginx/html/something ( – > 404)。

所以你必须select:

  1. 删除include /etc/nginx/conf.d/*.conf; 从您的nginx.conf(或删除default.conf )并将您的sites-enabled/default的server_name更改为localhost 。 然后你的请求会运行到你的configuration。

  2. 添加try_files $uri $uri/ /index.html;default.conf的位置,就像你在sites-enabled/default

我会推荐第一个解决scheme,不要包含default.conf ,并将您的server_name更改为localhost sites-enabled/config localhost 。 如果你以后需要你的真实的域名,你仍然可以使用正则expression式匹配localhost或你的域名。