我如何在 nginx 中将 WWW url 重定向到非 www url?

How do i redirect WWW url to non www url in nginx?

我的 nginx 配置有问题,我想重定向 www.yoursay.transport.nsw.gov.au to https://yoursay.transport.nsw.gov.au

这是我的配置

server {
    listen 443 ssl;

    ssl_certificate /etc/letsencrypt/live/yoursay.transport.nsw.gov.au/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yoursay.transport.nsw.gov.au/privkey.pem;

    # enable OCSP stapling to speed up first connect
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/letsencrypt/live/yoursay.transport.nsw.gov.au/chain.pem;

    if ($host = www.$server_name) {
    rewrite ^(.*) https://$server_name$request_uri? permanent;
    }
    server_name yoursay.transport.nsw.gov.au;

    root /var/www/ehq;

    add_header X-XSS-Protection "1; mode=block";
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload";

    include snippets/common_blocks.inc;
}

server {
    listen 80;

    server_name yoursay.transport.nsw.gov.au;
    return 301 https://yoursay.transport.nsw.gov.au$request_uri;
}

但还是不行,它说 ERR_CONNECTION_CLOSED

请帮我解决这个问题。

替换为:

    if ($host = www.$server_name) {
    rewrite ^(.*) https://$server_name$request_uri? permanent;
    }
    server_name yoursay.transport.nsw.gov.au;

有了这个:

    if ($host = www.yoursay.transport.nsw.gov.au) {
        return 301 https://yoursay.transport.nsw.gov.au$request_uri;
    }
    server_name yoursay.transport.nsw.gov.au www.yoursay.transport.nsw.gov.au;

解释:

当有人访问您的网站时,他们发送了 HTTP 请求 headers。其中之一是 Host,这是他们用来访问该网站的地址。它可以是 IP-address、www.example.comexample.comsomething.completely.irrelevantserver_name 选项定义了这个配置属于哪个 Host headers。所以我在server_name中加了www.yoursay.transport.nsw.gov.au,所以这个配置是给访客访问地址用的。您可能还希望在 HTTP 服务器块(侦听端口 80 的块)中重复此操作。