无法将https://www.example.com重定向到https://example.com

时间:2018-08-08 23:41:28

标签: ubuntu redirect nginx passenger lets-encrypt

我在Ubuntu上使用Nginx,并且能够将www.example.com重定向到https://example.com,但不能将SSL重定向到带有www子域的SSL。

这是我的/etc/nginx/sites-enabled/myapp.conf

# redirect non https traffic for the correct domains
server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80 default_server;
    listen [::]:80 default_server;

    server_name www.example.com;
    return 301 https://example.com$request_uri;
    return 404; # managed by Certbot

}

server {
    listen [::]:443 ssl ipv6only=on;
    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # server for these domains
    server_name example.com;

    # first try to serve the erb version.
    index index.html;

    # Tell Nginx and Passenger where your app's 'public' directory is
    root /var/www/myapp/code/public;

    # Turn on Passenger
    passenger_enabled on;
    passenger_ruby /usr/local/rvm/gems/ruby-2.5.1/wrappers/ruby;
}

即使在https://之后输入www网址,也可以将所有www子域流量重定向到根域吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

是的,添加以下服务器块:

# remove 'www'
server {
    listen 80;
    listen 443 ssl;
    server_name www.domain.com;
    return 301 https://example.com$request_uri;
}

这来自nginx docs