Turbo Host
Turbo Host

Reputation: 91

Rewriting HTTP to HTTPS in Nginx, using .conf settings

What I'm missing here?

server {
    listen 80;
    listen 443;

    if ($scheme = http) { rewrite ^(.*)$ https://domain.com$1 permanent; }
    if ($host ~* ^www\.) { rewrite ^(.*)$ https://domain.com$1 permanent; }
    ...
}

It gives me redirect loop error.

Upvotes: 0

Views: 72

Answers (1)

Patrick Lee
Patrick Lee

Reputation: 2013

I'll take a shot at this with the information available. When redirecting all requests from http to https, a separate server block for port 80 is a good idea. Similarly, when redirecting all requests from one hostname to another, a separate server block for each hostname is also a good idea.

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

    return 301 https://domain.com$request_uri;
}

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

    return 301 https://domain.com$request_uri;
}

server {
    listen 443;
    server_name domain.com;

    ...
}

So we're listening on port 80 for either hostname and redirecting to https://domain.com and also listening on port 443 for https://www.domain.com and redirecting those requests to https://domain.com as well. This keeps your Nginx configuration clear and easy to read.

Important: Please note that if your SSL certificate does not include www.domain.com, then requests to https://www.domain.com will result in a certificate error and rather nasty browser warnings. In this case, you should replace your certificate with one that includes both hostnames.

Upvotes: 1

Related Questions