您的当前位置:首页>全部文章>文章详情

Nginx实现二级域名或三级域名泛解析

发表于:2023-01-07 11:03:28浏览:761次TAG: #nginx #二级域名泛解析 #三级域名泛解析

部分应用场景下要求服务器根据客户输入的二级域名地址自动访问不同的页面,比如一个服务器放置了不同的业务,商城、官网等多个业务,又不想一个个配置server,这时候域名泛解析就用上了。那么Nginx是如何实现实现二级域名或三级域名泛解析?

方案一、Nginx 泛解析实现二级域名或三级域名泛解析

在nginx vhost配置文件里 修改 server_name 添加.domain.cn
如:server_name
.domain.com www.domain.com;

server {
        listen        80;
        server_name  *.saas.gougucms.com;
        root   "d:/wwwroot/gouguoa/public";
        location / {
            index  index.html index.htm index.php;
            #autoindex  on;
            if (!-e $request_filename) {
            rewrite  ^(.*)$  /index.php?s=/$1  last;
            break;
          }

        }
        location ~ \.php(.*)$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            #下面两句是给fastcgi权限,可以支挿?s=/module/controller/action的url访问模式
            fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            #下面两句才能真正支持 index.php/index/index/index的pathinfo模式
            fastcgi_param  PATH_INFO  $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
            include        fastcgi_params;
        }
}

完毕后记得重启nginx,service nginx restart
优点: 实现起来非常简单.
缺点: 可导致多个泛域名访问同一个页面.

方案二、nginx rewrite 实现二级或三级域名泛解析

在 nginx vhost配置文件server里 添加:

#if ($host ~* ^([^\.]+)\.([^\.]+\.[^\.]+)$) { # 二级域名 
 if ($host ~* ^([^\.]+)\.([^\.]+)\.([^\.]+)\.([^\.]+)$) {  #三级域名
        set $subdomain $1;
        set $domain $2;
}

location / { #修改为以下 
    rewrite ^/(.*)$  /index.php/$1/$subdomain  last;
        break;
    }