Search code examples
mod-rewritenginxhttpssubdomain

Rewrite https-URL before encryption


I need to rewrite URLs like *.lang.domain.com to lang.domain.com and I successfully did it using nginx rewrite module. I have wildcard certificate *.domain.com and it can't secure 4 level domain like test.lang.domain.com Main problem is when users type https://bla-bla.lang.domain.com in their browser they firstly get a notice about connection is not secure. Then they need to click advanced and proceed https://bla-bla.lang.domain.com (unsafe). After that they will be redirected to https://lang.domain.com. So my question is whether it is possible to do redirect before https-connection has been established in nginx? Or can it be achieved on some upper-level?

server {
    listen       80 default;
    server_name  www.domain.com domain.com *.domain.com;

    if ($host ~* "^.+\.(.+\.domain\.com)$") {
      set "$domain" "$1";
      rewrite ^(.*)$ https://$domain$uri permanent;
    }

    return 301 https://$host$request_uri;
}

server {
    listen       443 default;
    server_name  www.domain.com domain.com *.domain.com;

      if ($host ~* "^.+\.(.+\.domain\.com)$") {
      set "$domain" "$1";
    rewrite ^(.*)$ https://$domain$uri permanent;
    }

    ssl                  on;
    ssl_certificate     /etc/ssl/domain.com/domain.com.ca-bundle;
    ssl_certificate_key /etc/ssl/domain.com/domain.com.key;

    include "conf.d/ssl_settings.default";
    include "conf.d/redirect.ssl.default";
    include "conf.d/logger_front.default";

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HTTPS on;
        proxy_pass https://somestream;
    }
}

Solution

  • Redirects happen after a secure connection is established. So no, you cannot have a redirect to handle your particular case.