gpt4 book ai didi

angular - nginx.conf 中的 try_files 不工作

转载 作者:行者123 更新时间:2023-12-02 18:03:18 25 4
gpt4 key购买 nike

我正在使用 Angular 2 应用程序、nginx 和 docker。每次我用/site 重新加载页面时,它都会给我一个 404。我的服务器 block 现在看起来像这样:

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

站点启用/默认:

    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 中,您正在从两个位置加载其他配置:

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

第二个使用服务器名称 project.com 加载您的 sites.enabled/default 配置。

不过,第一个加载默认配置 default.conf,默认情况下它是 nginx docker 镜像的一部分。该配置看起来类似于

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

这意味着,如果您只是转到 localhost,则会提供 index.html,一切都会按预期进行。但是,一旦您尝试访问 localhost/something,Nginx 就会尝试查找不存在的文件/目录 /usr/share/nginx/html/something( -> 404)。

所以你必须选择:

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

  2. try_files $uri $uri//index.html; 添加到 default.conf 中的位置,就像在 中一样站点启用/默认

我会推荐第一个解决方案,不要包含 default.conf 并将您的 server_name 更改为 localhost 在您的 sites -启用/配置。如果您以后需要您的真实域,您仍然可以使用正则表达式来匹配本地主机或您的域。

关于angular - nginx.conf 中的 try_files 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com