1

I have an ssl certificate for www.domain.com. Obviously if someone goes to https: //domain.com, they will get an error from the browser about a certificate mismatch. Is it possible to setup the webserver to redirect requests from https:// domain.com to https:// www.domain.com?

In nginx, I've been trying variations of this, but to no avail:

server {
  listen   443;
  server_name www.domain.com domain.com;
  if ($host !~ www.domain.com) {
    rewrite ^/(.*) https://www.domain.com/$1 permanent;
  }
}

Edit: Just to clarify if anyone hits the site at via plain http, it's not a problem, I already can redirect them to https:// www.domain.com, which is correct. It's only if they manually type https:// domain.com, that I don't know how to do the redirection.

AJ01
  • 11

3 Answers3

2

Unfortunately, a redirection response can only take place after the SSL session has been established.

This is clearly a certificate issue; you need a certificate that contains www.domain.com with domain.com as the SAN (Subject Alternative Name). Most CA's give a single SAN for free, e.g., digicert.

Jack
  • 636
0
server {
 listen 443;
 servername www.domain.com domain.com;

 if ($host ~ ^(?!www)) {
        rewrite ^/(.*)$ http://www.$host/$1 permanent;
    }
}

second thought it might be better to use two server blocks:

server {
    listen 443;
    server_name  domain.com;
    rewrite ^(.*) http://www.example.com$1 permanent;
}

server {
    listen 443; 
    server_name  www.domain.com;
    hosting configuration here
}

EDIT: What about adding domain.com as a SubjectAltName in your SSL Cert so you don't have to rewrite. Perhaps ask your CA if this is possible?

Worst case, shell the $$ for a certificate to domain.com :D

iainlbc
  • 2,694
  • 19
  • 19
0

I use this to push users to a https service:

server {
  listen 80;
  server_name mail.polemon.org;
  rewrite ^(.*)$ https://mail.polemon.org$1 permanent;
}

and this is a catch-all rule:

server {
  listen 80;
  server_name polemon.org *.polemon.org;

  if ($host != polemon.org) {
    rewrite ^(.*)$ http://polemon.org$1 permanent;
  }
}

The catch-all has to be defined last, otherwise other subdomains won't work.

And here's another example, how to deal with people that have no Host: header line:

server {
  listen 80 default;
  server_name _;
  server_name_in_redirect off;

  root /var/www/jail/;
  index index.html;
}

As a side note, you can create certificates for wildcarded DNS names. Those are called "wild certificates", and even if they're valid, Firefox users still get warnings.

polemon
  • 595