Nginx在Docker中:位置配置不起作用

时间:2019-10-15 09:50:28

标签: angular docker nginx

附加docker文件。

FROM nginx:1.17.4-alpine

# copy artifact build from the 'build environment'
COPY ./dist /usr/share/nginx/html/
COPY ./default.conf /etc/nginx/conf.d/
# expose port 4202
EXPOSE 80

# run nginx
CMD ["nginx", "-g", "daemon off;"]

nginx config(default.conf)如下所示

server {
    listen       80;
    server_name  localhost;

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

    location /site {
        alias   /usr/share/nginx/html;
        index  index.html;  
    }

}

我使用docker run -p 4202:80 imageprocessor:v1成功构建并执行了Docker容器

但是,每当我尝试浏览localhost:4203 / site时,它都会重定向到localhost / site

为什么会这样?请帮忙。

1 个答案:

答案 0 :(得分:1)

Nginx不知道您要将端口4202映射到端口80。

当您提供URI /site时,Nginx将从外部重定向到/site/。然后根据index指令处理后一个URI。

您有两个选择:

1)避免Nginx生成外部重定向

location /site {
    alias   /usr/share/nginx/html;
    index  index.html;  

    rewrite ^/site$ /site/ last;
}

这应该为URI /site生成内部重定向。如果在此目录下还有其他目录,则可能需要添加一个更通用的解决方案。另外,相对URI(如果适用)将无法正确运行,因为结尾的/将丢失。

2)使用所需的端口号显式生成重定向

location /site {
    alias   /usr/share/nginx/html;
    index  index.html;  

    location ~ [^/]$ {
        if (-d $request_filename) {
            return 302 http://$http_host$uri/$is_args$args;
        }
    }
}

如果请求的URI指向目录,请使用所有必需的参数(包括结尾的/)来构造外部重定向。 $http_host的值应包括原始请求中的端口。有关所有Nginx变量,请参见this document