Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

In Nginx, how can I rewrite all http requests to https while maintaining sub-domain?

I want to rewrite all HTTP requests on my webserver to be HTTPS requests, I started with the following:
server {
listen 80;

location / {
rewrite ^(.*) //mysite.com$1 permanent;
}
...

One Problem is that this strips away any subdomain information (e.g., node1.mysite /folder), how could I rewrite the above to reroute everything to https and maintain the sub-domain?
by

2 Answers

akshay1995
here is the correct code:

server {
listen 80;
server_name my.domain.com;
return 301 https://$server_name$request_uri;
}

server {
listen 443 ssl;
server_name my.domain.com;
# add Strict-Transport-Security to prevent man in the middle attacks
add_header Strict-Transport-Security "max-age=31536000" always;

[....]
}
pankajshivnani123
Within the server block you can also do the following:

# Force HTTPS connection. This rules is domain agnostic
if ($scheme != "https") {
rewrite ^ https://$host$uri permanent;
}

Login / Signup to Answer the Question.