Nginx虚拟主机配置文件分别定义不同域名或IP的服务器块,包含各自根目录
基于域名的虚拟主机配置
-
修改
nginx.conf
文件:在http
块中添加include
指令,指定包含虚拟主机配置文件的目录。http { ... include /etc/nginx/conf.d/.conf; ... }
-
创建虚拟主机配置文件:在
/etc/nginx/conf.d/
目录下创建两个虚拟主机的配置文件,如site1.conf
和site2.conf
。 -
配置
site1.conf
:server { listen 80; server_name site1.example.com; location / { root /var/www/site1; index index.html; } }
-
配置
site2.conf
:server { listen 80; server_name site2.example.com; location / { root /var/www/site2; index index.html; } }
-
重启 Nginx 服务:使配置生效。
基于端口的虚拟主机配置
-
修改
nginx.conf
文件:同基于域名的配置,添加include
指令。 -
创建虚拟主机配置文件:同样在
/etc/nginx/conf.d/
目录下创建site1_port.conf
和site2_port.conf
。 -
配置
site1_port.conf
:server { listen 8080; server_name _; location / { root /var/www/site1_port; index index.html; } }
-
配置
site2_port.conf
:server { listen 8081; server_name _; location / { root /var/www/site2_port; index index.html; } }
-
重启 Nginx 服务:让配置生效。
常见问题与解答
问题 | 解答 |
---|---|
如何查看 Nginx 虚拟主机配置是否生效? | 可以使用 curl 命令或浏览器访问对应的域名或端口,查看是否能正确返回预期的内容。curl http://site1.example.com 或 curl http://localhost:8080 。 |
Nginx 虚拟主机配置中,server_name 可以配置多个域名吗? |
可以,在 server_name 指令后,使用空格分隔多个域名,表示该虚拟主机将响应这些域名的请求,`server_name site1.example.com www.site1.example. |
原创文章,发布者:酷盾叔,转转请注明出处:https://www.kd.cn/ask/66000.html