网站的目录结构为:
# tree /home/wwwroot/test.com
/home/wwwroot/test.com
├── bbs
│ └── index.html
└── www
└── index.html
2 directories, 2 files
/home/wwwroot/test.com为nginx的安装目录下默认的存放源代码的路径。
bbs为论坛程序源代码路径;www为主页程序源代码路径;把相应程序放入上面的路径通过;http://www.test.com 访问的就是主页http://bbs.test.com 访问的就是论坛,其它二级域名类推。
有2种方法,推荐方法一
方法一:
server {
#端口
listen 80;
#域名设置泛解析及子域“~^(?<subdomain>.+).test.com$”
server_name ~^(?<subdomain>.+).test.com$;
#日志
access_log /data/wwwlogs/test.com_nginx.log combined;
#首页索引
index index.html index.htm index.php;
#文件位置
root /home/wwwroot/test.com/$subdomain/;
#拦截错误输出下一行定义错误代码
fastcgi_intercept_errors on;
#错误代码和文件位置
error_page 404 = /404.html;
#目录无文件触发404
location / {
try_files $uri $uri/ =404;
}
#PHP
location ~ .php$ {
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
#缓存
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
expires 30d;
}
location ~ .*\.(js|css)?$ {
expires 7d;
}
}
方法二:
server {
#端口
listen 80;
#域名设置泛解析
server_name *.test.com;
#日志
access_log /home/wwwlogs/test.com_nginx.log combined;
#首页索引
index index.html index.htm index.php;
#文件位置
root /home/wwwroot/test.com/$subdomain/;
#拦截错误输出下一行定义错误代码
fastcgi_intercept_errors on;
#错误代码和文件位置
error_page 404 = /404.html;
#规则重写匹配规则 *.test.com
if ($host ~* ^([^\.]+)\.([^\.]+\.[^\.]+)$) {
set $subdomain $1;
set $domain $2;
}
#目录无文件触发404
location / {
try_files $uri $uri/ =404;
}
# PHP
location ~ .php$ {
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
#缓存
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
expires 30d;
}
location ~ .*\.(js|css)?$ {
expires 7d;
}
}
转自https://linuxeye.com/430.html