【问题标题】:How to test nginx subdomains on localhost如何在 localhost 上测试 nginx 子域
【发布时间】:2012-04-23 03:00:25
【问题描述】:

我想在将配置上传到服务器之前测试 nginx 子域。我可以在本地主机上测试它吗?我试试

server {
    listen       80;
    server_name  localhost;

    location / {
        proxy_pass http://localhost:8080;
    }
}

server {
    listen       80;
    server_name  sub.localhost;

    location / {
        proxy_pass http://localhost:8080/sub;
    }
}

而且它不起作用。我应该更改我的主机文件以使其正常工作吗?另外,在将站点上传到服务器后,我应该更改 DNS 记录并添加 sub.mydomain.com 吗?

【问题讨论】:

    标签: nginx subdomain


    【解决方案1】:

    是的,将“127.0.0.1 sub.localhost”添加到您的主机文件中。该子必须以某种方式解决。应该可以的。

    然后,一旦您准备好上网,是的,为子域 sub 添加 a 或 cname 记录。

    当我使用 proxy_pass 时,我还包括来自 nginx 的 proxy.conf。 http://wiki.nginx.org/HttpProxyModule

    【讨论】:

    • /etc/hosts 中的行应该是127.0.0.1 localhost sub.localhost
    【解决方案2】:

    在基于 Linux 的操作系统中,只需编辑为 sudo /etc/hosts 文件并将 127.0.0.1 localhost 更改为 127.0.0.1 *.localhost

    所以在/etc/nginx/sites-enabled/<environment>/<your_project_name> 编辑server_name 键为<subdomain>.localhost

    重新加载 nginx 和网络服务。

    $ sudo service nginx reload
    $ sudo service networking reload
    

    然后在网址栏尝试http://<subdomain>.localhost

    它对我有用。

    更新

    在我看来,更好的解决方案是创建一个仅在子域不存在时才响应的虚拟服务器,地址为 /etc/nginx/sites-enabled/development/default,作为默认服务器(请记住,您只能将一个服务器定义为默认服务器)。

    server {
      listen 80 default_server;
      root /var/www/html/errors/404;
      server_name *.localhost *.<host-name>;
    
      location / {
        index subdomain.html;
      }
    
    }
    

    确保在nginx.conf(通常在/etc/nginx/nginx.conf)中包含include /etc/nginx/sites-enabled/**/*; 到此虚拟服务器工作。如果没有,放上去然后运行$ sudo service nginx reload

    在这种情况下,不必将*.localhost 放入/etc/hosts,而只需将localhost

    【讨论】:

    【解决方案3】:

    对于拥有自己域名的公共网络服务器,您只需在 DNS 配置中使用 CNAME 记录添加规范名称:

    CNAME    *    example.com.
    

    完成后,设置您的 nginx 设置

    server_name  *.example.com example.com;
    

    在您的本地设置中,您可以为 nginx 保留相同的配置,但除非您有本地 DNS 设置,否则您必须编辑 /etc/hosts 文件并手动添加每个子域。通配符在 /etc/hosts 文件中不起作用。

    127.0.0.1  abc.example.com def.example.com ghi.example.com
    

    通常建议使用 .local 作为本地域的命名空间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      相关资源
      最近更新 更多