Nginx SSL 连接错误

Nginx SSL 连接错误

我正在尝试将网站从 HTTP 迁移到 HTTPS,但是我的 nginx(版本:1.10.3)配置似乎不起作用。

期望以下行为:

  • http://www.example.com/path/to/content应该重定向到https://example.com/path/to/content
  • http://example.com/path/to/content应该重定向到https://example.com/path/to/content
  • https://www.example.com/path/to/content应该重定向到https://example.com/path/to/content

使用我当前的配置,浏览器无法使用 HTTPS 连接到该网站:

server {
    listen 80;
    listen [::]:80;

    server_name www.example.com example.com;

    # redirects both www and non-www to https
    rewrite ^(.*) https://www.example.com$1 permanent;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name example.com;

    # redirects non-www to www
    rewrite ^(.*) https://www.example.com$1 permanent;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;

    charset utf-8;

    # rest of my config
}
  • 我必须改变什么才能实现上述行为?
  • 为了保持页面“活跃”并让我测试它,是否可以在第一步接受(然后重定向)HTTP 请求?
  • 我的网站拥有非常好的 SEO 排名(索引为“http://www.example.com”),因此正确的重定向是必须的。

答案1

此配置使得您所要求的:

server {
    listen 80;
    listen [::]:80;

    server_name www.example.com example.com;

    # redirects both www and non-www to https
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name www.example.com;

    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;

    # redirects www to non-www
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name example.com;

    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;

    charset utf-8;

    # rest of my config
}

我将rewrite其改为return,因为这样效率更高一些。使用 时,return必须使用$request_uri将请求路径和参数放入重定向 URL 中。

然后我改变了server_name example.com;withlisten 443;块以提供网站的实际内容,并server_name www.example.com;使用listen 443;来进行重定向。

答案2

请尝试使用以下方法并更新其余 SSL 信息:

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

对于 SSL,提供 SSL 密钥路径:

server {  
 listen   443 ssl;
 ssl on;  
 ssl_prefer_server_ciphers   on;  
 ssl_protocols TLSv1 TLSv1.1 TLSv1.2;  
  ssl_certificate      /path of certificate;  
 ssl_certificate_key  /path of server.key;
}

相关内容