Nginx:本地主机上的路由

问题描述 投票:0回答:1

我想配置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-onehttp://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和default.conf文件夹的html文件,然后重新启动:docker restart my-nginx

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

nginx routing nginx-config
1个回答
0
投票

好,最后我明白了...

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,上帝保佑他。希望它能对别人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.