Simple HTTP-to-HTTPS AND domain.com-to-WWW Redirect Using Nginx

Simple HTTP-to-HTTPS AND domain.com-to-WWW Redirect Using Nginx

The basic layout

You are running Nginx as a webserver or reverse proxy, where you will be terminating SSL.

You are looking for the following functionality:

Below is a very simple sample virtual host config that will allow you to do just that. In this example, I am listening on HTTP and HTTPS and redirecting all HTTP/non-WWW traffic to the HTTPS/WWW URL. In this case, I am using Nginx to reverse proxy traffic to a Node.js server on localhost, but you can easily add document root/index directives to serve the content.

/etc/nginx/sites-available/example.conf:
server {
        listen 80;
        server_name  domain.com www.domain.com;
        return 301 https://www.domain.com$request_uri;
}

server {
	listen 443;
	server_name domain.com;
	return 301 https://www.domain.com$request_uri;
}

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

        ssl on;
        ssl_certificate /etc/ssl/certs/certificate.crt;
        ssl_certificate_key /etc/ssl/private/privatekey.pem;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1.2;
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES128-GCM-SHA256:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!MD5:!PSK:!RC4";
        ssl_prefer_server_ciphers on;
        ssl_session_cache shared:SSL:10m;

        location / {
            proxy_pass  http://localhost:8001;
        }
}

Stay tuned for a version using an AWS Elastic Loadbalancer for SSL termination that passes traffic to an Nginx HTTP backend and requires IP:PORT health checks. Update: here it is.

Leave a Reply