简体   繁体   中英

Nginx Redirect HTTP to HTTPS and WWW to Non-WWW

I'm having issues with this config:

#=========================#
# domain settings #
#=========================#

# Catch http://domain, and http://www.domain
server {
        listen 80;
        server_name www.domain domain;

        # Redirect to https://domain
        return 301 https://domain$request_uri;
}

# Catch https://www.domain
server {
        listen 443;
        server_name www.domain;

        # Redirect to https://domain
        return 301 https://domain$request_uri;
}

# Catch https://domain
server {
        listen 443;
        server_name domain;

        root /usr/share/nginx/domain;
        index index.html index.htm;

        ssl on;
        ssl_certificate /etc/nginx/ssl/server.crt;
        ssl_certificate_key /etc/nginx/ssl/server.key;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
        ssl_prefer_server_ciphers on;

        location / {
                try_files $uri $uri/ =404;
        }
}

Something is wrong with the 3rd server directive. I get a SSL connection error. But when I comment our that section everything works fine. But I want www to redirect to non-www over https also

Can anyone spot the problem?

Adding the

ssl on;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
ssl_prefer_server_ciphers on;

In the 3rd server directive fixed this issue.

The Nginx configuration snippet below will enable you effectively redirect all http traffic to https while stripping any eventual www prefix.

As such, your site will strictly be available over https and without the www prefix.

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name www.example.com example.com;

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

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    if ($host = www.example.com) {
        return 301 https://example.com$request_uri;
    }

    server_name www.example.com example.com;

    # SSL configuration
    # Other configurations
}

With reference to if is evil , do note that it is safe to use the if directive as it is not used in a location context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM