LNMP--Nginx 默认虚拟主机
2018-01-09
LNMP--Nginx 默认虚拟主机
在之前的笔记中说过,apache 中有一个默认的虚拟主机(虚拟主机配置文件的第一个),无论什么域名只要指向到这台机器就会访问到这个主机。其实,在 nginx 里也有这样的默认虚拟主机,但它是通过一个配置来标记哪个虚拟主机是默认的。
在 nginx.conf 主配置文件的最后加入如下一行,表示启用虚拟主机。
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
server
{
listen 80;
server_name localhost;
index index.html index.htm index.php;
root /usr/local/nginx/html;
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
}
}
include /usr/local/nginx/conf/vhosts/*.conf;
}
创建该目录和对应虚拟主机配置文件:
[root@localhost ~]# mkdir /usr/local/nginx/conf/vhosts
[root@localhost ~]# cd !$
cd /usr/local/nginx/conf/vhosts
[root@localhost vhosts]# vim default.conf
server
{
listen 80 default_server;
server_name test.com;
index index.html index.htm index.php;
root /tmp/tmp;
deny all;
}
这里通过 listen 80 后的 default_server 来确认默认虚拟主机,通过 deny all 来禁掉访问。
创建一个可访问的虚拟主机:
添加虚拟主机配置文件,和 apache 不一样的是,多个虚拟主机配置文件是分开写在对应目录下的多个文件中,而不是 apache 中一个文件的多个字段。
server
{
listen 80;
server_name 123.com www.123.com;
index index.html index.htm index.php;
root /usr/local/nginx/html;
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
}
}
在对应目录中建立 index.php
检查和重新加载
[root@localhost vhosts]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost vhosts]# /usr/local/nginx/sbin/nginx -s reload
修改 hosts 文件
[root@localhost vhosts]# vim /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.94.128 www.123.com www.test.com
使用 curl 命令检测
[root@localhost vhosts]# curl www.123.com -I
HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Tue, 28 Jun 2016 22:16:41 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 28 Jun 2016 16:48:28 GMT
Connection: keep-alive
ETag: "5772aa5c-264"
Accept-Ranges: bytes
[root@localhost vhosts]# curl www.123.com/2.php
test php scripts.[root@localhost vhosts]#
[root@localhost vhosts]# curl www.test.com -I
HTTP/1.1 403 Forbidden
Server: nginx/1.8.0
Date: Tue, 28 Jun 2016 22:17:09 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive