nginx通配符子域ssl重写

时间:2012-08-13 11:04:46

标签: redirect nginx ssl-certificate wildcard-subdomain

拥有通配符dns子域记录。使用仅域验证SSL证书。 需要以这种方式设置nginx重写规则:

http://site.com   => https://site.com

http://*.site.com => http://*.site.com

我想这就是这样的

server {
    listen  80;
    server_name site.com *.site.com;
    if ($host ~* "^([^.]+(\.[^.]+)*)\.site.com$"){
        set $subd $1;
        rewrite ^(.*)$ http://$subd.site.com$1 permanent;
        break;
    }
    if ($host ~* "^site.com$"){
        rewrite ^(.*)$ https://site.com$1 permanent;
        break;
    }
    #rewrite    ^ https://$server_name$request_uri? permanent;
    charset utf-8;
}

server {

    listen   443;

    server_name  site.com;
    ssl On;
    ssl_certificate     /root/site.com.crt;
    ssl_certificate_key /root/site.com.key;

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:8888;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/site$fastcgi_script_name;
        fastcgi_param  QUERY_STRING     $args;
        include fastcgi_params;
    }

    location / {
        root   /var/www/site;
        index  index.php index.html;
        if ($host !~ ^(site.com)$ ) {
            return 444;
        }
        try_files $uri $uri/ /index.php?$args;
    }
}

无限循环。让这个工作的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

您应该将服务器块重写为两部分。 第一部分仅针对域“site.com”并且重定向到https 第二部分,对于所有其他域名,“* .site.com”

server {
    listen  80;
    server_name site.com;
    rewrite ^(.*)$ https://site.com$1 permanent;
}

server {
    listen  80;
    server_name *.site.com;
    #etc... rewrites not necessary
}

所以,你的nginx.conf将是:

server {
    listen  80;
    server_name site.com;
    rewrite ^(.*)$ https://site.com$1 permanent;
}
server {
    listen  80;
    server_name *.site.com;
    charset utf-8;
    # etc ...
}

server {

    listen   443;

    server_name  site.com;
    ssl On;
    ssl_certificate     /root/site.com.crt;
    ssl_certificate_key /root/site.com.key;

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:8888;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /var/www/site$fastcgi_script_name;
        fastcgi_param  QUERY_STRING     $args;
        include fastcgi_params;
    }

    location / {
        root   /var/www/site;
        index  index.php index.html;
        if ($host !~ ^(site.com)$ ) {
            return 444;
        }
        try_files $uri $uri/ /index.php?$args;
    }
}