7

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!

romo
  • 171
  • 1
  • 1
  • 3

3 Answers3

3

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.

  • 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;
}
Ashish Gupta
  • 305
  • 2
  • 6