问题原文
原帖链接 · Cerin · CC BY-SA 4.0
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?
已采纳解答
原帖链接 · Pothi Kalimuthu · CC BY-SA 4.0
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
# ...
# ...
}
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
