这里有新鲜出炉的 Nginx 开发从入门到精通, 程序狗速度看过来!
Nginx web 服务器
Nginx 是一个高性能的 HTTP 和 反向代理 服务器, 也是一个 IMAP/POP3/SMTP 代理服务器 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的, 第一个公开版本 0.1.0 发布于 2004 年 10 月 4 日其将源代码以类 BSD 许可证的形式发布, 因它的稳定性丰富的功能集示例配置文件和低系统资源的消耗而闻名
下面小编就为大家分享一篇 nginx 配置虚拟主机, 实现在一个服务器可以访问多个网站的方法, 具有很好的参考价值, 希望对大家有所帮助一起跟随小编过来看看吧
在一台服务器上, 访问不同的网站
通常有两种区分方式:
1. 通过监听的端口号
2. 通过域名
1. 通过端口访问不同的主机:
Nginx 的配置文件:
/usr/local/nginx/conf/nginx.conf
Centos 文件默认编码格式 latin1
查看编码格式的命令: :set fileencoding
- #user nobody;
- worker_processes 1;
- #error_log logs/error.log;
- #error_log logs/error.log notice;
- #error_log logs/error.log info;
- #pid logs/nginx.pid;
- events {worker_connections 1024;}
- ## 一个 http 节点
- http {
- include mime.types;
- default_type application/octet-stream;
- #log_format main '$remote_addr - $remote_user [$time_local]"$request" '
- # '$status $body_bytes_sent"$http_referer" '
- # '"$http_user_agent" "$http_x_forwarded_for"';
- #access_log logs/access.log main;
- sendfile on;
- #tcp_nopush on;
- #keepalive_timeout 0;
- keepalive_timeout 65;
- #gzip on;
- #server 节点, 即 你需要访问网站的配置
- #一个 server 节点, 就是一个虚拟主机
- server {
- listen 80; #监听的端口号, 访问网站 默认是 80 端口
- server_name localhost; #即访问的域名
- #charset koi8-r;
- #access_log logs/host.access.log main;
- location / { #定位
- root html; #定位的是 nginx 根目录下的 html 文件夹
- index index.html index.htm; #设置网站首页
- }
- }
- }
此时 可以配置多个 server, 也就是配置了不同的主机
添加虚拟主机:(通过端口号 区别)
- server {
- listen 81;
- server_name localhost;
- #charset koi8-r;
- #access_log logs/host.access.log main;
- location / {
- root html-81;
- #nginx 根目录下 新建的 html81 文件夹
- index index.html index.htm;
- ``
- }
编辑好文件之后, 我们重新加载配置文件
通过命令: ./nginx -s reload
效果:
我们知道, 当一个服务器上配置多个网站时, 我们不可能通过端口号来区分它们, 所以接下来 我需要通过域名来区分
2. 通过域名区分不同的虚拟主机
什么是域名??
域名就是网址
例如: www.baidu.com
通常我们在访问域名的时候, 我们需要通过 dns 服务器解析域名
Dns 服务器: 把域名解析为 ip 地址保存的就是域名和 ip 的映射关系
一个域名对应一个 ip 地址, 一个 ip 地址可以被多个域名绑定
本地测试可以修改 hosts 文件
修改 window 的 hosts 文件:(C:\Windows\System32\drivers\etc)
可以配置域名和 ip 的映射关系, 如果 hosts 文件中配置了域名和 ip 的对应关系, 不需要走 dns 服务器!!!!
在刚刚的 nginx.conf 文件下 继续配置:
- server {
- listen 80;
- server_name www.taobao.com;
- #charset koi8-r;
- #access_log logs/host.access.log main;
- location / {
- root html-taobao;
- index index.html index.htm;
- }
- }
- server {
- listen 80;
- server_name www.baidu.com;
- #charset koi8-r;
- #access_log logs/host.access.log main;
- location / {
- root html-baidu;
- index index.html index.htm;
- }
- }
- }
域名的配置:
- 192.168.25.148 www.test.com
- 192.168.25.148 www.yiyou.com
重启 nginx 服务
观察下效果:
以上这篇 nginx 配置虚拟主机, 实现在一个服务器可以访问多个网站的方法就是小编分享给大家的全部内容了, 希望能给大家一个参考, 也希望大家多多支持 PHPERZ
来源: http://www.phperz.com/article/18/0319/362599.html