活到老学到老  

记录遇到问题的点点滴滴。

Nginx泛解析匹配绑定域名子目录

7年前发布  · 2114 次阅读
  nginx 

以ubuntu为例:

网站的/data/wwwroot目录结构为:

.
└── ubuntu.local
    ├── a
    │   └── index.php
    └── b
        └── index.php

3 directories, 2 files

/data/wwwroot/ubuntu.local

a为测试A目录

b为测试B目录

把相应程序放入上面的路径通过

http://a.ubuntu.local 访问的就是A目录

http://b.ubuntu.local 访问的就是B目录

其它二级域名类推。

实现方法有两种。

server {
    listen 80;
    server_name ~^(?<subdomain>.+).ubuntu.local$;

    access_log /data/logs/ubuntu.local_nginx.log combined;
    index index.html index.htm index.php;

    root /data/wwwroot/ubuntu.local/$subdomain;

    
    location ~ \.php$ {
    	include snippets/fastcgi-php.conf;
    
    	# With php5-cgi alone:
    	#fastcgi_pass 127.0.0.1:9000;
    	# With php5-fpm:
    	fastcgi_pass unix:/var/run/php5-fpm.sock;
    }

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
        expires 30d;
    }
    
    location ~ .*\.(js|css)?$ {
        expires 7d;
    }
}

方法二:

server {
    listen 80;
    server_name *.ubuntu.local;
    
    access_log /data/logs/ubuntu.local_nginx.log combined;
    index index.html index.htm index.php;
    
    if ($host ~* ^([^\.]+)\.([^\.]+\.[^\.]+)$) {
        set $subdomain $1;
        set $domain $2;
    }
    
    location / {
        root/data/wwwroot/$domain/$subdomain;
        index index.php index.html index.htm;
    }

    location ~ \.php$ {
    	include snippets/fastcgi-php.conf;
    
    	# With php5-cgi alone:
    	#fastcgi_pass 127.0.0.1:9000;
    	# With php5-fpm:
    	fastcgi_pass unix:/var/run/php5-fpm.sock;
    }
    
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
        expires 30d;
    }
    
    location ~ .*\.(js|css)?$ {
        expires 7d;
    }
}