如何从HTTP同一端口重定向到https nginx的反向代理(How to redirect on

2019-07-21 16:37发布

我使用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问题 ,但迄今没有奏效。

Answer 1:

发现东西是正常工作:

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;
        }
}


Answer 2:

你确定你的解决方案的工作? 它监听的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;
    }
}


Answer 3:

您可以

  1. 用$ SERVER_NAME避免硬编码再次您正在访问的域名(DRY)
  2. 使用回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
    ...
}


Answer 4:

这为我工作:

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