Nginx HTTPS configuration redirects to faulty URL

conquester asked:

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?

My answer:


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.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.