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?

1
  • 1
    There are mistakes in your configuration other than the one you asked about; read Pitfalls carefully to learn about and correct these. Commented Nov 2, 2016 at 1:35

1 Answer 1

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.

2
  • I replaced _ with example.com and www.example.com and it worked. Commented Nov 2, 2016 at 1:41
  • However, using $host is less secure because you're allowing a permanent redirect based on what the browser provides. This is a great start to a XSS attack. Commented Nov 16, 2017 at 15:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.