3

My goal is to have nginx primarily return a check for all requested URLs that start with http:// and/or contain //www., and 301 redirect them to the URL where //www. is replaced by // and http:// replaced by https://.

In short, all requests, if necessary, to be redirected to their non-www, SSL version, so that subsequently, all other non-default servers, serving as reverse-proxies for specific domains, will then always get https, non-www requests.

How do I do this?

3

The http server does not require a specific certificate, so all domains can be redirected to https non-www with a single server block.

For example:

server {
    listen 80;
    server_name ~^(www\.)?(?<domain>.+)$;
    return 301 https://$domain$request_uri;
}

See this document for more.


The https servers probably require a specific certificate for each domain. To redirect from www to non-www, a specific certificate should be valid for both name variants. You should use two server blocks for each specific domain, the existing one and another to perform the redirect.

For example:

server {
    listen 443 ssl;
    server_name www.example.com;

    ssl_certificate     /path/to/example.com.crt;
    ssl_certificate_key /path/to/example.com.key;

    return 301 https://example.com$request_uri;
}
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /path/to/example.com.crt;
    ssl_certificate_key /path/to/example.com.key;

    ... this is the existing server block for this domain ...
}

See this document for more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.