Nginx配置虚拟主机具体的代码配置

Vps 上安装了 Nginx。但是我们还需要Nginx配置虚拟主机,那么要如何才能进行Nginx配置虚拟主机呢?接下来我们就详细看看有关虚拟主机在Nginx上的配置问题。用多个子域名,每个子域名到不同的目录。

如:

 
 
 
  1. http {   
  2. server {   
  3. listen 80;   
  4. server_name a.chenlb.com;   
  5. access_log logs/a.access.log main;   
  6. server_name_in_redirect off;   
  7. location / {   
  8. index index.html;   
  9. root /home/www/host_a/;   
  10. }   
  11. }   
  12. server {   
  13. listen 80;   
  14. server_name b.chenlb.com;   
  15. access_log logs/b.access.log main;   
  16. server_name_in_redirect off;   
  17. location / {   
  18. index index.html;   
  19. root /home/www/host_b/;   
  20. }   
  21. }   
  22. }   
  23. http {  
  24. server {  
  25. listen 80;  
  26. server_name a.chenlb.com;  
  27. access_log logs/a.access.log main;  
  28. server_name_in_redirect off;  
  29. location / {  
  30. index index.html;  
  31. root /home/www/host_a/;  
  32. }  
  33. }  
  34. server {  
  35. listen 80;  
  36. server_name b.chenlb.com;  
  37. access_log logs/b.access.log main;  
  38. server_name_in_redirect off;  
  39. location / {  
  40. index index.html;  
  41. root /home/www/host_b/;  
  42. }  
  43. }  

结果发现用 b.chenlb.com 还是指到 host_a 目录。后来看了官方示例:http://wiki.Nginx.org/NginxVirtualHostExample,提到有个 default 的匹配,如:

 
 
 
  1. http {   
  2. server {   
  3. listen 80 default;   
  4. server_name _;   
  5. access_log logs/default.access.log main;   
  6. server_name_in_redirect off;   
  7. location / {   
  8. index index.html;   
  9. root /var/www/default/htdocs;   
  10. }   
  11. }   
  12. }   
  13. http {  
  14. server {  
  15. listen 80 default;  
  16. server_name _;  
  17. access_log logs/default.access.log main;  
  18. server_name_in_redirect off;  
  19. location / {  
  20. index index.html;  
  21. root /var/www/default/htdocs;  
  22. }  
  23. }  

加上这个 default 就可使 a.chenlb.com 和 b.chenlb.com 正常工作了。以上就是对Nginx配置虚拟主机的详细介绍。

【编辑推荐】

  1. Nginx服务器的性能依然强劲
  2. Nginx配置中运行与启动的详细介绍
  3. Nginx缓存如何避免传统缓存的错误
  4. Nginx php如何解决502 Bad Gateway错误
  5. Nginx proxy反向代理的十五大技术特点
THE END