1、使用dnf安装nginx
dnf install nginx -y
2、在/etc/nginx/conf.d 目录下创建两个配置文件:---- cd命令切换
[root@www ~]# cd /etc/nginx/conf.d
2.1、www.chengke.com.conf,文件内容如下: --- vim命令
#命令:
[root@www conf.d]# vim www.chengke.com.conf
#相关内容
server {
listen 80; #注释: ---- 默认是80,该命令可以不写
server_name www.chengke.com;
root /opt/www.chengke.com;
}
2.2、www.chengke.net.conf,文件内容如下: --- vim命令
server {
listen 80;
server_name www.chengke.net;
root /opt/www.chengke.net;
}
3、在 /opt/ 目录下创建以下目录
mkdir /opt/www.chengke.{com,net} -p
4、分别在这两个目录下创建index.html
它们的内容如下:
echo "www.chengke.com" > /opt/www.chengke.com/index.html
#echo输出/打印打印内容
#echo的参数
#-n 输出后不自动换行(默认echo最后会换行)
#-e 开启转义字符识别(\n换行,\t指标空格)
#-E 关闭转义(默认)
echo "www.chengke.net" > /opt/www.chengke.net/index.html
5、启动nginx服务
---修改了配置文件,需要重启生效
systemctl start nginx
6、域名映射
vim /etc/hosts
#/etc/hosts 本地域名解析表,优先级比 DNS 服务器更高
#在文件末尾写入如下:
.....
192.168.10.141 www.chengke.com
192.168.10.141 www.chengke.net
7、访问测试
[root@localhost conf.d]# curl http://www.chengke.com
www.chengke.com
[root@localhost conf.d]# curl http://www.chengke.net
www.chengke.net
8、root和alias指令***
root:指定web的家目录,在定义 location 的时候,文件的绝对路径等于 root + location
server {
listen 80;
server_name www.example.com;
location / {
root /opt/www.example.com;
}
location /test.html
alias /opt/www.example.com/test.html;
}
}
#location 匹配浏览器请求的 URI 路径,不同路径走不同处理规则
location /test.html {
alias /opt/www.example.com;
}
curl http://www.example.com/test.html
此时请求不到,出现的301跳转,将alias别名改为root,是可以访问的。原因:
当用的是别名alias ,这个路径的末尾的文件没有创建
root和alias的区别:
如果使用的是root来配置服务的根目录,那么,请求地址会追加到指定家目录的后面。如果请求跟,则访问的是家目录下的index.html;如果请求/test.html,则访问的是家目录下的test.html;
location / {
root /opt/www.example.com;
}
如果使用的是alias来配置服务的目录,那么,请求路径需要手动写入到目录之后;
location /test.html {
alias /opt/www.example.com/test.html;
}
总结:用root的 家目录路径不用写全;
root /opt/www.example.com;
用alias的 家目录路径要写完整;
alias /opt/www.example.com/test.html;