Nginx HTTPS 重定向循环与多个域

Nginx HTTPS 重定向循环与多个域

我知道还有其他问题有类似的主题,但我找不到任何可以解决我特定问题的解决方案。这里的区别是多个域和不同的站点。

我已为 Nginx 设置了多个域名:example1.comexample2.com。此外还有“默认”主机文件,其中包含“欢迎使用 Nginx!”默认网页

我尝试了几种不同的配置,包括:

# 1
server {
   server_name example2.com www.example2.com;
   listen 80;
   return 301 https://example2.com$request_uri;
}
server {
    server_name example2.com www.example2.com;
    listen 443 default_server;

    ssl_certificate /etc/letsencrypt/live/example2.com/fullchain.pem; 
    ssl_certificate_key /etc/letsencrypt/live/example2.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

# 2
server {
    server_name example2.com www.example2.com;
    listen 80;
    listen 443

    return 301 https://example2.com$request_uri;

    ssl_certificate /etc/letsencrypt/live/example2.com/fullchain.pem; 
    ssl_certificate_key /etc/letsencrypt/live/example2.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

}

1结果是:

  • http://例子2.com 重定向至https://例子2.com 显示“欢迎”页面
  • http://例子1.com 重定向至https://例子2.com 显示“欢迎”页面
  • https://例子1.com 显示示例的实际内容1.com

2结果是:

  • http://例子2.com 存在重定向循环
  • https://例子2.com 存在重定向循环
  • http://例子1.com 重定向至http://例子2.com 存在重定向循环
  • https://例子1.com 显示示例的实际内容1.com

我不能将内容放在example2.com默认的“欢迎”文件夹中,否则会影响example1.com

答案1

感谢 Richard Smith,我知道我是怎么搞砸的。我没有正确包含根位置。以下是正确的文件,希望它能帮助其他人:

# example2.com.conf:
server {
    server_name example2.com www.example2.com;
    listen      80;
    return      301 https://example2.com$request_uri;
    # What I was missing:
    root            /var/www/example2-com;
}
server {
    server_name     example2.com www.example2.com;
    listen      443 ssl;# default_server;

    # What I was missing:
    root            /var/www/example2-com;

    ssl_certificate /etc/letsencrypt/live/example2.com/fullchain.pem; 
    ssl_certificate_key /etc/letsencrypt/live/example2.com/privkey.pem;
    include         /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam     /etc/letsencrypt/ssl-dhparams.pem;

}

# example1.com.conf:
server {
    server_name example1.com www.example1.com;
    listen      80;
    return      301 https://example1.com$request_uri;

    # What I was missing:
    root            /var/www/example1-com;
}
server {
    server_name     nerd.ink www.nerd.ink;
    listen      443 ssl; # default_server;

    # What I was missing:
    root            /var/www/example1-com;

    ssl_certificate /etc/letsencrypt/live/example1.com/fullchain.pem; 
    ssl_certificate_key /etc/letsencrypt/live/example1.com/privkey.pem;
    include         /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam     /etc/letsencrypt/ssl-dhparams.pem;
}

相关内容