5

This is my first setup with nginx and I'm using it to proxy to nodejs. HTTP is on port 3000, and HTTPS is on port 3001.

If I go to http://test.domain.com it loads the regular unsecure pages. If I go to https://test.domain.com it loads the secure pages. But I want it to redirect from non-https to https.

What's wrong with my config? This is the whole domain.conf file I'm using.

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

server {
    listen 443 ssl;

    server_name test.domain.com;

    ssl_certificate /etc/nginx/ssl/domain.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;

   location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header HOST $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass https://127.0.0.1:3001;
      proxy_redirect off;
   }
}

I have restarted nginx multiple times.

Thanks!

3
  • Did you restart nginx? – Michael Hampton Jul 2 '14 at 18:09
  • Yes, multiple times – romo Jul 2 '14 at 18:22
  • Same problem here. Did you figure it out? – Matt Jul 7 '16 at 22:52
2

You can use rewrite in your http server block

server {
    listen 80;
    server_name test.domain.com;
    rewrite ^ https://$server_name$request_uri? permanent;
}
1

Missing ";" at the end of line. (or just a broken copy/paste?)

    server_name test.domain.com;

I think you have another server_block operating at default server that overrides this one without valid server name

Tips:

  1. If you want to catch all http requests with one global server block, use default_server:

    listen 80 default_server;
    
  2. Your can use more variables ;)

    return 301 https://test.domain.com$request_uri;
    

    to

    return 301 https://$host$request_uri;
    

    Do not use rewrite, return is fastest.

1
  • Thanks for call out, I had been missing the semi-colon from my server_name line as well and it was really boggling why it was serving up the default directory instead of redirecting. What was annoying is that "sudo service nginx testconfig" will report OK when it's missing. – Melikoth Sep 26 '17 at 18:56
-1

Add these line in port 80 configuration for auto redirect to https with params, remove return and adjust the port if needed.

if ($http_x_forwarded_proto != 'https') {
  #rewrite ^(.*) https://$host$1 redirect;
}
2

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.