Nginx Redirect HTTP to HTTPS and WWW to Non-WWW

核能气质少年 提交于 2020-12-29 14:07:26

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/33047999/nginx-redirect-http-to-https-and-www-to-non-www

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!