我使用nginx的反向代理,我要强制请求转换成HTTPS,所以如果用户想使用HTTP访问URL,他将被自动重定向到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;
}
}
我试过很多东西,也阅读它的职位,包括这个serverfault问题 ,但迄今没有奏效。
发现东西是正常工作:
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;
}
}
你确定你的解决方案的工作? 它监听的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;
}
}
您可以
- 用$ SERVER_NAME避免硬编码再次您正在访问的域名(DRY)
- 使用回301位便于阅读(一个Web开发应该知道这个HTTP状态代码)
注:我把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
...
}
这为我工作:
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;
}
...
}
文章来源: How to redirect on the same port from http to https with nginx reverse proxy