1

How do you redirect certain paths on an Nginx-hosted site from http to https?

I want to ensure everyone visiting the path "/admin" is behind https. Googling finds me several guides about how to add global rewrite rules, but I can't find anything about how to add a rewrite rule for a specific site.

All the examples I see for doing this use the server{} syntax, which isn't allowed in a site's configuration file. What's the site-specific syntax equivalent?

I have a load balancer that accepts 443 connections, does all the SSL handling, and forwards requests to my server on port 80, do Nginx doesn't actually need to serve requests on port 443. It just needs to see that requests are originally coming from http and redirect the user to https. Previously, I was doing this redirect in Apache using a rewrite rule like:

RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 

What's the equivalent in Nginx?

2
  • 1
    Why are you not running the whole website on https? Commented Sep 22, 2018 at 1:09
  • Indeed, there are quite a few attacks one can make against your users because you don't run the entire website on https. Having https on only part of the site was never really a good idea; it's absolutely critical that you don't do it now. Commented Sep 22, 2018 at 3:04

1 Answer 1

2

The equivalent configuration in Nginx is...

if ( $x-forwarded-proto != 'https' ) return https://$host$request_uri; }

Please be aware that "using if is not evil" if used correctly.

How do you redirect certain paths on an Nginx-hosted site from http to https?

location /pathtoredirect { return https://$host$request_uri; }

So, for your particular situation, the solution would go something like this...

location /admin { if ( $x-forwarded-proto != 'https' ) return https://$host$request_uri; } # directives to process /admin when accessed via https # ... # ... } 
4
  • Generally in Nginx you avoid "if" statements where possible Commented Sep 22, 2018 at 0:50
  • The link is already mentioned in the answer, with a note on it. Commented Sep 22, 2018 at 0:54
  • Suggest that the if statement is not needed since the location block should be within the http location block. Of course if one location block serves both http and https (which I don't do personally) then you have little choice but to use if. Commented Sep 22, 2018 at 1:09
  • @Tim You have little choice when nginx is behind a load balancer that terminates TLS, as the original post stated. Commented Sep 22, 2018 at 3:02

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.