当前位置: 首页 > 文档资料 > 优质文章推荐 v1 >

如何配置 nginx 实现虚拟主机

优质
小牛编辑
117浏览
2023-12-01

nginx安装好之后一般会在/etc/nginx/目录下有nginx.conf文件和conf.d目录,这其实已经帮我们预留了虚拟主机要准备的内容。

看下nginx.conf文件,里面有这样一行:

include /etc/nginx/conf.d/*.conf;

那么也就是说ngixn启动都会自动加载conf.d目录下以.conf结尾的所有配置文件

ok,我们直接干掉nginx.conf里面server组的全部内容,只留几句重要内容,像这样:

user  nginx;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    client_max_body_size 20M;
    include /etc/nginx/conf.d/*.conf;
}

同时在conf.d下创建mywebsite.conf文件,内容如下:

log_format logformat '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
server {
    listen       80;
    server_name  localhost;
    index index.html;
    root /data/httpdir/mywebsite/web;
    access_log /data/httpdir/logs/mywebsite.log logformat;
    error_log /data/httpdir/logs/mywebsite.error_log;
}

创建/data/httpdir/mywebsite/web/index.html文件内容如下:

<html>
<body>
<h1>hello world!</h1>
</body>
</html>

创建/data/httpdir/logs目录,并修改权限:

chmod -R 777 /data/httpdir/logs/

执行

[root@centos7vm nginx]# service nginx restart

重启ngxin,如果发现重启不了,很有可能是service有问题,见这个帖子http://www.oschina.net/question/139930_228663

所以干脆直接执行ngxin来启动nginx服务就没问题了,如下:

[root@centos7vm nginx]# nginx

可以看到进程已经存在了:

[root@centos7vm nginx]# ps aux|grep nginx
root      12775  0.0  0.1 109552  1980 ?        Ss   07:14   0:00 nginx: master process nginx
nginx     12776  0.0  0.3 109960  3044 ?        S    07:14   0:00 nginx: worker process

这时访问:http://localhost/如下

虚拟主机现在刚刚实现了一个站点,让我们再创建一个,复制mywebsite.conf到mywebsite2.conf,内容改成:

log_format logformat2 '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
server {
    listen       80;
    server_name  localhost2;
    index index.html;
    root /data/httpdir/mywebsite2/web;
    access_log /data/httpdir/logs/mywebsite2.log logformat2;
    error_log /data/httpdir/logs/mywebsite2.error_log;
}

注意:这里listen端口不变,server_name做了修改,log_format做了修改(不然会认为命名重复),root目录做了修改,日志文件名做了修改

为了能让本机识别出localhost2对应的是哪个ip,我们修改/etc/hosts文件,添加一行

127.0.0.1   localhost2

同时我们还需要创建网页文件,创建/data/httpdir/mywebsite2/web目录并在web目录下创建index.html文件如下:

<html>
<body>
<h1>HaHa</h1>
</body>
</html>

重新加载nginx配置:

[root@centos7vm conf.d]# nginx -s reload

这时我们访问http://localhost2/,如下:

重新访问http://localhost/,依然是

这便是虚拟主机,同一个ip同一个端口,不用域名可以访问不同的网站