一、准备
[root@server1 ~]# grep -Ev "#|^$" /usr/local/nginx/conf/nginx.conf //查看这个文件里不以#号开头,没有空行的内容
[root@server1 ~]# cp /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.bak //备份
[root@server1 ~]# grep -Ev "#|^$" /usr/local/nginx/conf/nginx.conf.bak > /usr/local/nginx/conf/nginx.conf //将文件里面以#开头,没有空行的内容清除
[root@server1 ~]# vim /usr/local/nginx/conf/nginx.conf //查看
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
二、基于域名的虚拟主机
[root@server1 ~]# mkdir /gaofan
[root@server1 ~]# echo "I am tdr" > /gaofan/index.html
[root@server1 ~]# vim /usr/local/nginx/conf/nginx.conf //在http模块下添加新的server模块
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server{
listen 80;
server_name www.tdr.com;
root /gaofan;
location / {
index index.html;
}
}
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
[root@server1 ~]# /usr/local/nginx/sbin/nginx
[root@server1 ~]# /usr/local/nginx/sbin/nginx -s reload //重载服务
[root@server1 ~]# vim /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.1.100 www.tdr.com
[root@server1 ~]# curl www.tdr.com //访问测试
I am tdr
三、多虚拟主机
一个服务器上同时部署多个项目,为了方便维护,可以将server模块单独抽 离出来创建conf文件,然后在主配置文件中使用include添加外部配置,这 样让操作更加模块化
[root@server1 ~]# mkdir /usr/local/nginx/conf.d //创建新目录
[root@server1 ~]# touch /usr/local/nginx/conf.d/gaofan.conf
[root@server1 ~]# sed -n '12,19p' /usr/local/nginx/conf/nginx.conf > /usr/local/nginx/conf.d/gaofan.conf //nginx.conf中创建的server复制到gaofan.conf这个文件中
[root@server1 ~]# vim /usr/local/nginx/conf/nginx.conf //删除nginx.conf中原有的自定义server模块
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
include ../conf.d/*.conf; //添加include,这里也可以写成绝对路径,可以自由选择
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
[root@server1 ~]# /usr/local/nginx/sbin/nginx -s reload //重载
浏览器测试