nginx使用子域和裸域重定向

时间:2020-08-07 17:22:31

标签: nginx redirect ubuntu-16.04

我正在尝试在我的nginx配置中找出我的域的重定向。我有这三个域名:

domain.com //points to server 1
www.domain.com //points to hubspot server 2, no a record to change naked domain
app.domain.com //points to server 1
  • 我需要domain.com重定向到www.domain.com
  • 我需要app.domain.com保持未重定向

我正在尝试的所有操作都是将所有URL重定向到www.domain.com

我在做什么错了?

一次尝试,重定向所有内容:

server {
    listen 80;
    server_name domain.com;
    return 301 www.domain.com;
}

server {
    root var/www/domain/public;
    index index.php index.html;
    server_name app.domain.com;
}

另一种尝试,重定向所有内容:

server {
    listen 80;
    root var/www/domain/public;
    index index.php index.html;
    server_name domain.com app.domain.com;
    return 301 www.domain.com
}

这只是完全破坏了我的配置:

server {
    listen 80;
    root var/www/domain/public;
    index index.php index.html;
    server_name domain.com app.domain.com;
  
    location domain.com {
      return 301 www.domain.com;
    }
}

更新:

我已经更新了配置,这样说:

server {
        server_name     domain.com;
        return          301 $scheme://www.domain.com$request_uri;

}

server {
    root /var/www/domain/public;
    index index.php index.html;
    server_name app.domain.com;


    location / {
            try_files $uri $uri/ /index.php?$query_string;
    }

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

这是当前正在发生的事情:

  • domain.com和app.domain.com都指向我们的Google云服务器。我希望app.domain.com继续指向此处,并使domain.com到301重定向到hubspot
  • www.domain.com指向我们的中心服务器

以上情况当前发生的是:

  • www.domain.com到正确的位置(集中点)
  • app.domain.com转到正确的位置(谷歌云)
  • domain.com仍然到达错误的位置(谷歌云),但是使用curl -I -L domain.com表示它被重定向到了正确的位置301!我很困惑。

我的一些朋友在为我测试地址时说,他们已经正确301重定向了,但有一些没有(包括我自己)

这是curl命令的打印输出:

HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.3 (Ubuntu)
Date: Sun, 09 Aug 2020 22:33:49 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: ht tp://www.domain.com/

HTTP/1.1 200 OK
Date: Sun, 09 Aug 2020 22:33:49 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 54566
Connection: keep-alive

1 个答案:

答案 0 :(得分:0)

www.example.comapp.example.com使用相同的根目录?如果是,请参见下面的示例。

对于example.com,如果您需要重定向到www子域:

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

对于www.example.comapp.example.com,而无需重定向并从/var/www/example/public输出数据:

server {
    listen 80;
    server_name www.example.com app.example.com;

    root /var/www/example/public;
    index index.php index.html;
}
相关问题