wisetc / practice

Practice conclusion
5 stars 0 forks source link

Nginx 不同端口映射情形时重定向 uri 端口不正确 #27

Open wisetc opened 5 years ago

wisetc commented 5 years ago

使用 docker 镜像 nginx:1.17.0-alpine 构建容器。将主机端口 8080 映射到容器的 80 端口,由于 采用默认的配置访问目录名不加 / 时,不会返回其中的 index 内容,所以需要额外配置。如下的配置适用于同端口映射的情形,当宿主机的端口和容器的端口不一致时,访问 http://localhost:8080/abc, 则会重定向到 http://localhost/abc/, 这显然不是我们想要的结果。

    listen 80;
    location / {
        index  index.html index.htm;
        try_files $uri $uri/ =404;
    }

于是我去问搜索引擎,终于找到了此情形下的配置。

    location / {
        index  index.html index.htm;
    }

    location ~ ^.*[^/]$ {
        try_files $uri @rewrite;
    }
    location @rewrite {
        return 302 $scheme://$http_host$uri/;
    }

参考 https://serverfault.com/questions/739498/nginx-rewrite-on-docker-machine-when-host-port-container-port