mtmacdonald
mtmacdonald

Reputation: 15070

How to redirect from http to https and example.com to www.example.com

I need help with the following redirect example, using NGINX:

I've read related questions but still can't get both redirects to work together.

I've tried this configuration, but I get an error when trying to load the site: The connection was interrupted.

# 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;
  }
 }

Upvotes: 0

Views: 861

Answers (1)

Maxim Dounin
Maxim Dounin

Reputation: 6755

You have no SSL certificate defined in the server{} block for https://example.com, and this is what causes your problems. You have to add a certificate there. (And, BTW, this information should be in your error log. It's always a good idea to look into it if something goes wrong.)

Usually it's the same cert as for www.example.com, so you have to use:

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;
}

Note well that ssl on; is not needed as you are using listen ... ssl;, see here for details.

Upvotes: 3

Related Questions