2012-04-10 63 views
16

我想在将配置上传到服务器之前测试nginx子域。我可以在本地主机上测试它吗?我试试如何测试localhost上的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; 
    } 
} 

而且它不起作用。 Shoulld我改变我的主机文件,以使其工作?另外,上传站点后,我应该更改DNS记录并添加sub.mydomain.com?

回答

15

是的,将'sub.localhost 127.0.0.1'添加到您的主机文件。这个部分必须以某种方式解决。这应该工作。

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

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

+0

是的,谢谢,它的工作原理。 – madhead 2012-05-02 11:17:09

5

对于自己的域名的公开的Web服务器,你只需要使用一个CNAME记录在您的DNS配置中添加一个规范名称:

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作为本地域名称空间。

1

在基于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 restart 

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

它适用于我。

UPDATE

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

server { 
    listen 80 default_server; 
    root /var/www/html/errors; 
    server_name *._; 

    location/{ 
    index 404.html; 
    } 

} 

确保在nginx.conf(一般为/etc/nginx/nginx.conf)包含include /etc/nginx/sites-enabled/**/*;到该虚拟服务器的工作。如果没有,则放入并运行$ sudo service nginx restart

在这种情况下,没有必要把*.localhost/etc/hosts,但只有localhost