4

Hello I am trying to redirect all my requests to use https. I have created a server block that listens on port 80 (http) and I want to redirect the user to use https:// however I am unsure how to obtain the hostname.

here is my server block

server
{
    listen 80;
    server_name : *.example.org
    return 301 https://{{hostname}}$request_uri
}

I know that the URI is accessed by $request_uri but I am unsure how to obtain the hostname.

Do you append them by having them next to each other with no space?

1

1 Answer 1

5

The link that Michael Hampton posted explains the variables in more detail but here is a direct answer.

server
{
    listen 80;
    server_name *.example.com;
    return 301 https://$host$request_uri;
}

You can see it work using curl and looking at the header.

http://bob.example.com to https://bob.example.com

[root@hm1 conf.d]# curl --head bob.example.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.9.13
Date: Wed, 06 Apr 2016 02:01:24 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: https://bob.example.com/
Strict-Transport-Security: max-age=15780000; preload
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff

http://alice.example.com to https://alice.example.com

[root@hm1 conf.d]# curl --head alice.example.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.9.13
Date: Wed, 06 Apr 2016 02:01:39 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: https://alice.example.com/
Strict-Transport-Security: max-age=15780000; preload
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
1
  • you can also do $scheme which would change the answer to return 301 $scheme://$host$request_uri;
    – Edward
    Mar 16, 2018 at 13:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .