两种方法可以在Nginx环境下配置子域名,形成多站点,第一种方法 前面已经介绍过了,就是为每个子域名建立一个.conf配置文件;当子域名很多时,这种方法的就显现弊端了。这里介绍第二种方法。
1、假设已经向服务器添加了一个新域名 test.com,下面介绍添加子域名 abc.test.com 和 sub.test.com。在test.com 的配置文件中 添加如下内容:
server {
listen 80;
server_name *.test.com abc.test.com sub.test.com; #多个子域名用空格隔开
root D:/dev/$host; # 定义根目录,这里的$host对应域名
access_log logs/test.access.log;
error_log logs/test.error.log;
location / {
root D:/dev/$host/;
index index.php index.html index.htm;
}
# server static files directly
#直接支持静态文件,图片、样式文件等
location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html)$ {
access_log off;
expires 30d;
}
# 可根据需要为不同的CGI进程设置不同的服务信息
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_intercept_errors on;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
2、修改hosts文件,使子域名abc.test.com 和 sub.test.com 都指向本机。
3、这里的根目录为 D:/dev/$host,其中$host是当前域名,那么当访问 abc.test.com时,实际访问的文件夹是 D:/dev/abc.test.com;访问 sub.test.com时,实际访问的是 D:/dev/sub.test.com。故一定要存在相应的目录文件,否则回报404错误。
4、重启Nginx,分别在对应的文件夹中放入测试文件index.php,访问相应子域名,测试是否成功。