如何在NginX中将www.example.com重定向到example.com?

时间:2017-04-27 05:48:13

标签: redirect nginx

当我们打开example.com(没有HTTPS)时,网站加载得非常好但是当我们打开www.example.com(没有HTTPS)时会打开“欢迎使用nginX”,但我不需要这个,我们想要即使网址为example.com,也要打开www.example.com

注意:我们的网站有“HTTPS”,当我们打开example.com时,它会被重定向到https://example.com

注意:当我们打开https://www.example.com时,网站加载良好,但当网址为www.example.comhttps://www.example.com时,网址未被重定向。

我们在AWS上使用Ubuntu。

2 个答案:

答案 0 :(得分:1)

为此,我建议您编辑nginx配置文件(通常在/ etc / nginx / sites-enabled / you-example-config中),添加返回301,如here所示,类似于:

server {
    listen 80;
    listen 443;
    server_name www.example.com example.com;
    return 301 https://example.com$request_uri;
    #[...ssl settings go here, certs etc....]
}
server {
    listen 443;
    server_name example.com;
    # [...ssl and main settings go here...]
}

这将导致所有请求返回https://example.com

答案 1 :(得分:0)

您是否为每个选项定义了单独的服务器? 请参阅下面的示例代码段。 您的问题看起来非常类似于this questionthis question ,它们都有更多信息,我不会在此处复制粘贴。

此链接也可能有所帮助 creating-nginx-rewrite-rules

server {
    listen 80;
    listen 443 ssl;
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
    listen 80;
    server_name example.com;
    # here goes the rest of your config file
    # example 
    location / {

        rewrite ^/cp/login?$ /cp/login.php last;
        # etc etc...

    }

}

$scheme是协议(HTTP或HTTPS),$request_uri是包含参数的完整URI。

相关问题