user785179
user785179

Reputation: 917

Nginx: rewrite rule to redirect to https page

I want to redirect my login page to https so that users do not inadvertently enter their credentials through the unencrypted network. How do I do something like the below?

# nginx.conf
server {
  server_name example.org;
  rewrite http://*.example.org/login https://example.org/login;
}

This works for http://example.org/login, but it does not work for http://www.example.org/login

Rewrite rule output for

rewrite http://.*\.?example.org/login https://example.org/login;

Rewrite debug output:

*2 "http://.*\.?example.org/login" does not match "/login", client: XXX.XXX.XX.72, server: example.org, request: "GET /user HTTP/1.1", host: "example.org"

Upvotes: 1

Views: 2022

Answers (1)

Sébastien Renauld
Sébastien Renauld

Reputation: 19662

I deleted my original answer as it was quite a lot easier. You'll need a location block and an if for this to work, along with a catchall server domain. Structure as follows:

 server {
   server_name example.org;
   server_name *.example.org;
   location /login {
       if ( $scheme = http ) {
          rewrite ^ https://example.org/login last;
       }
   }
 }

As much as I hate using ifs in nginx coming, this time, it's necessary.

Upvotes: 4

Related Questions