【问题标题】:How to redirect from http to https and example.com to www.example.com如何从 http 重定向到 https 和 example.com 到 www.example.com
【发布时间】:2014-10-02 00:34:16
【问题描述】:

我需要以下重定向示例的帮助,使用 NGINX:

我已阅读 related questions 但仍然无法让两个重定向一起工作。

我已尝试过此配置,但在尝试加载站点时出现错误:连接中断

# Redirect any http:// request to https://www.example.com
server {
  listen 80;
  return 301 https://www.example.com$request_uri;
}

# Redirect http://example.com to https://www.example.com
server {
  listen 443 ssl;
  server_name example.com
  return 301 https://www.example.com$request_uri;
}

server {
  listen  443;
  server_name www.example.com;

  ssl on;
  ssl_certificate /foo.crt;
  ssl_certificate_key /foo.key;

  root /foo/;
  index index.php index.html index.htm;

  location / {
    try_files $uri $uri/ /index.php$is_args$args;
  }

  # pass the PHP scripts to FastCGI server listening on /var/run/php5-fpm.sock
  location ~ \.php$ {
    try_files $uri /index.php =404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
  }
 }

【问题讨论】:

    标签: redirect nginx


    【解决方案1】:

    您没有在server{} 块中为https://example.com 定义 SSL 证书,这就是导致您的问题的原因。您必须在那里添加证书。 (顺便说一句,此信息应该在您的错误日志中。如果出现问题,最好查看它。)

    通常它与 www.example.com 的证书相同,因此您必须使用:

    server {
      listen 443 ssl;
      server_name example.com;
      ssl_certificate /foo.crt;
      ssl_certificate_key /foo.key;
      return 301 https://www.example.com$request_uri;
    }
    

    请注意,您使用的是listen ... ssl;,因此不需要ssl on;,有关详细信息,请参阅here

    【讨论】:

    • 除此之外,我还漏掉了 server_name 行末尾的分号。谢谢。
    猜你喜欢
    • 2020-09-24
    • 2016-01-16
    • 2011-05-18
    • 1970-01-01
    • 2017-12-21
    • 2011-07-06
    • 2011-08-12
    • 1970-01-01
    • 2015-09-25
    相关资源
    最近更新 更多