我在Nginx上使用反向代理,我想强制请求进入HTTPS,因此如果用户想要使用http访问该网址,他将自动重定向到HTTPS。
我也在使用非标准端口。
这是我的nginx反向代理配置:
server {
listen 8001 ssl;
ssl_certificate /home/xxx/server.crt;
ssl_certificate_key /home/xxx/server.key;
location / {
proxy_pass https://localhost:8000;
proxy_redirect off;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Ssl on;
proxy_set_header X-Forwarded-Proto https;
}
}
我尝试了很多东西并且还阅读了有关它的帖子,包括this serverfault question,但到目前为止还没有任何工作。
答案 0 :(得分:66)
找到效果很好的东西:
server {
listen 8001 ssl;
ssl_certificate /home/xxx/server.crt;
ssl_certificate_key /home/xxx/server.key;
error_page 497 https://$host:$server_port$request_uri;
location /{
proxy_pass http://localhost:8000;
proxy_redirect off;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Ssl on;
}
}
答案 1 :(得分:4)
您确定您的解决方案有效吗?它正在倾听8001 ssl。它会接受http请求吗?
我是这样做的:
server {
listen 80;
server_name yourhostname.com;
location / {
rewrite ^(.*) https://yourhostname.com:8001$1 permanent;
}
}
然后进入你的配置:
server {
listen 8001 ssl;
ssl_certificate /home/xxx/server.crt;
ssl_certificate_key /home/xxx/server.key;
location / {
proxy_pass https://localhost:8000;
proxy_redirect off;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Ssl on;
proxy_set_header X-Forwarded-Proto https;
}
}
答案 2 :(得分:1)
你可以
注意:我把443用于https服务器。如果你真的想要,你可以听8001。
server {
listen 80;
server_name your_hostname.com;
return 301 https://$server_name$request_uri;
}
...
server {
listen 443 ssl;
server_name your_hostname.com
...
}
答案 3 :(得分:1)
这对我有用:
server {
listen 80;
server_name localhost;
...
if ($http_x_forwarded_proto = "http") {
return 301 https://$server_name$request_uri;
}
location / {
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8080;
}
...
}
答案 4 :(得分:0)
这是我的方法,我认为这很干净,并允许您在需要时添加其他位置。我在$ http_x_forwarded_proto属性上添加了一个测试,如果为true,则在NGINX反向代理设置上将所有HTTP流量强制为HTTPS
upstream flask_bootstrap {
server flask-bootstrap:8000;
}
server {
# SSL traffic terminates on the Load Balancer so we only need to listen on port 80
listen 80;
# Set reverse proxy
location / {
proxy_pass http://flask_bootstrap;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect http://localhost/;
# Permanently redirect any http calls to https
if ($http_x_forwarded_proto != 'https') {
return 301 https://$host$request_uri;
}
}
}