更改 nginx 中的 localhost 主机名

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

我有多个本地站点,我想将 nginx 配置为每个网站都有不同的主机。

在 /var/www 中我有 2 个站点:site1 和 site2

然后在 /etc/nginx/sites-available/ 中,我为每一个创建了 2 个不同的配置服务器。我有文件 site1 和 site2,其内容如下:

server {
        listen 80;

        root /var/www/site1;
        index index.html index.htm;

        server_name localhost;

        location / {
                try_files $uri $uri/ /index.html;
        }
}

server {
            listen 7777;

            root /var/www/site2;
            index index.html index.htm;

            server_name localhost;

            location / {
                    try_files $uri $uri/ /index.html;
            }
    }

我使用

http://localhost:80
(站点 1)和
http://localhost:7777
(站点 2)访问它们。效果很好。我还可以在 /etc/hosts 中添加主机名,如下所示:

127.0.0.1 localhost site1 site2

我可以使用

http://site1:80
http://site2:7777
访问它们。但我必须始终访问端口号。我想通过
http://site1
http://site2
访问它们。

有解决办法吗?

nginx
3个回答
7
投票

你已经明白了,但让我解释一下它为什么有效。

第一个站点

site1
应该可以正常工作,因为默认的
http
端口是 80,而这就是
site1
正在监听的端口,所以
http://site1.com
应该可以正常工作。

site2
的第二个配置文件正在监听端口
7777
,所以执行正常的
http://site2.com
是行不通的,实际上它可能会选择你的默认网站并提供服务,因为nginx没有尝试匹配
server_name
与配置中的那个,因为端口不匹配。

您应该在端口 80 上创建所有网站,nginx 会自行匹配并知道要服务器的站点,除非它是

https
网站,那么您将使用端口
443
,这是默认的 ssl 端口


0
投票

即使我们在本地运行 docker 容器,我们是否也必须编辑 Windows 主机文件?


-1
投票

为 Windows 10 设置

/etc/hosts

转到

c:\Windows\System32\Drivers\etc\hosts
目录并使用文本编辑器打开文件,然后添加此行
127.0.0.1 localhost site1 site2

然后打开任意浏览器并点击

site1/
。确保它是
http://
,而不是
https://

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