如何从http重定向到https和example.com到www.example.com

时间:2014-08-08 13:47:44

标签: redirect nginx

我需要使用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;
  }
 }

1 个答案:

答案 0 :(得分:3)

您在https://example.comserver{}区块中没有定义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;
}

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

相关问题