Question

Have a wildcard dns subdomain record. Using domain-only validation SSL certificate. Need to set nginx rewrite rules in that way:

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

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

I guess it is something like this

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;
    }
}

It loops infinitely. What is the correct way to get this working ?

Was it helpful?

Solution

You should rewrite your server block into two parts. First part only for domain "site.com" and following redirection to https Second part, for all other domains, "*.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
}

So, your nginx.conf would be:

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;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top