Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

nginx - HTTPS redirect www to non www

I got 2 domains and its supposed to work from same directory. While redirecting from http with/without www works perfectly, https www to non www don't work. Here is my config file:

server {
    listen 80;
    server_name domain1.com www.domain1.com;
    return 301 https://domain1.com$request_uri;
}

server {
    listen 80;
    server_name domain2.com www.domain2.com;
    return 301 https://domain2.com$request_uri;
}

server {
    listen 443 ssl;
    server_name www.domain1.com;
    return 301 https://domain1.com$request_uri;
    ssl_certificate /etc/letsencrypt/live/domain1.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain1.com/privkey.pem;
}

server {
    listen 443 ssl;
    server_name www.domain2.com;
    return 301 https://domain2.com$request_uri;
    ssl_certificate /etc/letsencrypt/live/domain1.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain1.com/privkey.pem;
}

server {
    listen 443 ssl;
    server_name domain1.com;
    root /var/www/domain1.com;
    index index.php index.html index.htm;
    ssl_certificate /etc/letsencrypt/live/domain1.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain1.com/privkey.pem;

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

    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    }

}

server {
    listen 443 ssl;
    server_name domain2.com;
    root /var/www/domain1.com;
    index index.php index.html index.htm;
    ssl_certificate /etc/letsencrypt/live/domain1.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain1.com/privkey.pem;

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

    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    }

}

Can you tell me what could be wrong with it? SSL certificate domain1.com have got inside certificates for all domains, include with/without WWW.

question from:https://stackoverflow.com/questions/65886412/https-redirect-www-to-non-www

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In case if someone will face to same issue, removal of "ssl" abbreviate fixed it. So instead of listen 443 ssl; in 301 server blocks change to listen 443;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...