I'm using nginx for my node.js app. I've used the Digitalocean tutorial to config the nginx and https use. Right now, the following works:

http:// example.com -> https:// example.com
example.com --> https:// example.com
www.example.com --> https:// example.com
http:// www.example.com --> https:// example.com

but when i enter https:// www.example.com, it does not redirect to https:// example.com

here is my nginx congif on sites-available/default

# HTTP - redirect all requests to HTTPS:
server {
        listen 80;
        listen [::]:80 default_server ipv6only=on;
        return 301 https://$host$request_uri;

# HTTPS - proxy requests on to local Node.js app:
server {
        listen 443;
        server_name ezplan.ir;

        ssl on;
        # Use certificate and key provided by Let's Encrypt:
        ssl_certificate /path/to.crt;
        ssl_certificate_key /path/to.key;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers 'SSL STUFF';

        # Pass requests for / to localhost:8080:
        location / {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://localhost:8080/;
                proxy_ssl_session_reuse off;
                proxy_set_header Host $http_host;
                proxy_cache_bypass $http_upgrade;
                proxy_redirect off;

can anyone help me do this redirection as well?

  • You should use return 301 https://example.com$request_uri in your first server block, so that a request to http://www.example.com would go directly to https://example.com, without going to https://www.example.com first. Otherwise rsp's answer below fixes the main issue. – Tero Kilkanen Mar 29 '17 at 6:09

You can do two blocks for https - with and without www:

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

server {
    listen 443;
    server_name example.com;
    // ...
    // your normal config here - proxy to node and all that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.