1

I have Nginx working with gunicorn as an upstream server. I am trying to configure the site to use HTTPS and force all HTTP requests to use SSL.

Here is my nginx configuration in /etc/nginx/conf.d/site.conf:

server {
       listen         80;
       server_name    _;
       return         301 https://$server_name$request_uri;
}



server {
    listen       443 ssl;
    server_name  _;

    ssl_certificate      /etc/ssl/nginx/cert_chain.crt;
    ssl_certificate_key  /etc/ssl/nginx/private.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    add_header Strict-Transport-Security "max-age=31536000";

    location / {
        proxy_pass         http://127.0.0.1:8000/;
        proxy_redirect     off;

        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }

}

After installing this config whenever I go to: https://example.com/page.html then it returns the page as expected.

But when I use: https://example.com/ then the browser weirdly redirects to: https: //_/

This problem also happens when I use the the HTTP version of the site at www.example.com

How can I rewrite the above configuration to make it work properly?

techraf
  • 4,243
  • 8
  • 29
  • 44
conquester
  • 153
  • 2
  • 6
  • 1
    There are mistakes in your configuration other than the one you asked about; read [Pitfalls](https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/) carefully to learn about and correct these. – Michael Hampton Nov 02 '16 at 01:35

1 Answers1

2

Your configuration specifically states that HTTP requests should be redirected to https://_/.

       server_name    _;
       return         301 https://$server_name$request_uri;

Because server_name is set to _, that is what is used for $server_name.

The variable you should be using instead of $server_name is $host. This will always have something sensible based on what the browser requested (provided the browser requested something sensible).

Ideally, though, a server block with server_name _; shouldn't serve anything other than an error page. Rather, you should have server blocks for your actual domain names. Such a configuration prevents unintended access to your server via plain IP address or hostnames that aren't configured in nginx or your web application.

Michael Hampton
  • 244,070
  • 43
  • 506
  • 972