【问题标题】:Nginx: route on localhostNginx:本地主机上的路由
【发布时间】:2020-04-25 21:44:24
【问题描述】:

我想配置 Nginx 以在 localhost 上路由多个项目而不接触 hosts 我电脑上的文件。

即Nginx 至少应该处理路径

  1. http://localhost/project-one

  2. http://localhost/project-two

我找到了一个example,但它在我的情况下不起作用:

# /etc/nginx/conf.ddefault.conf
server {
    listen       80;
    # server_name  localhost;
    index  index.html index.htm;

    location ~ ^/project-one {
        root   /usr/share/nginx/html/project-one;
        # index  index.html index.htm;
    }

    location ~ ^/project-two {
        root   /usr/share/nginx/html/project-two;
        # index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

如果我只将一个location 设置为一个斜线并且需要root,它就可以工作:

# /etc/nginx/conf.ddefault.conf
server {
    listen       80;
    # server_name  localhost;
    index  index.html index.htm;

    location / {
        root   /usr/share/nginx/html/project-one;
        # index  index.html index.htm;
    }
}

使用此配置,它会显示来自project-one 目录http://localhost 的html 文件。

我正在使用 Docker 进行测试:

docker run --rm --name my-nginx -p 80:80 -v $(pwd)/sites:/etc/nginx/conf.d -v $(pwd)/html:/usr/share/nginx/html -d nginx

所以我可以分别在本地目录中为 Nginx 和 html 文件夹更改 default.conf 文件,然后重新启动:docker restart my-nginx

如何在不接触hosts文件的情况下为多个根正确配置多个位置?

【问题讨论】:

  • root 的值与 URI 连接以形成文件的路径。该值应为/usr/share/nginx/html,因为project-oneproject-two 是URI 的一部分。详情请见this document
  • @RichardSmith,非常感谢,在您与 root 分享这个清晰的示例之前,这对我来说是相当难以承受的。谢谢!

标签: nginx routing nginx-config


【解决方案1】:

好吧,终于明白了……

server {
    listen       80;
    # server_name  localhost;
    index  index.html index.htm;

    location ~ ^/project-one {
        root   /usr/share/nginx/html;
        # index  index.html index.htm;
    }

    location ~ ^/project-two {
        root   /usr/share/nginx/html;
        # index  index.html index.htm;
    }
}

现在它按我的预期工作了:

http://localhost/project-one

http://localhost/project-two

每个请求相对路由到不同的文件夹:

/usr/share/nginx/html/project-one/index.html

/usr/share/nginx/html/project-two/index.html

感谢@RichardSmith。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    相关资源
    最近更新 更多