【问题标题】:How to forward particular requests to https in Nginx如何在 Nginx 中将特定请求转发到 https
【发布时间】:2017-07-09 23:18:08
【问题描述】:

我是这样配置Nginx的:

#/etc/nginx/conf.d/default.conf
server {
        listen 8081 default_server;
        listen [::]:8081 default_server ipv6only=on;

        server_name localhost;

        listen 443 ssl;

        location /site/ {
            proxy_pass http://127.0.0.1:8084/;
        }

        # 404 occured
        #location /site/secure/ {
        #    proxy_redirect http://localhost:8081/site/secure/ https://localhost/site/secure/;
        #}


        location / {
            root /srv;
            index index.html index.htm;

            try_files $uri $uri/ /index.html;
        }

        ssl_certificate /etc/nginx/ssl/nginx.crt;
        ssl_certificate_key /etc/nginx/ssl/nginx.key;

}

我已启用 https。 我有几个网址:

http://127.0.0.1:8081/site/secure/
http://127.0.0.1:8081/sute/path1/...
http://127.0.0.1:8081/sute/path2/...

我只想将http://127.0.0.1:8081/site/secure/* 请求重定向到https://127.0.0.1/site/secure/*,这样用户就不能通过简单的http 使用这个url。

但是当我使用这个重定向运行 Nginx 时:

location /site/secure/ {
    proxy_redirect http://localhost:8081/site/secure/ https://localhost/site/secure/;
}

我收到 404 响应:

<html>
    <head>
        <title>404 Not Found</title>
    </head>
    <body bgcolor="white">
        <center>
            <h1>404 Not Found</h1>
        </center>
        <hr>
        <center>nginx/1.4.6 (Ubuntu)</center>
    </body>
</html>

如何配置 nginx 以正确的方式将某些请求重定向到 https?

【问题讨论】:

    标签: redirect nginx https


    【解决方案1】:

    proxy_redirect 是错误的指令。您需要使用return 301 https://... 之类的东西将客户端从http 移动到https

    最简洁的方法是使用两个server 块,并使用include 指令引入通用配置语句。例如:

    server {
        listen 8081 default_server;
        listen [::]:8081 default_server ipv6only=on;
    
        include /path/to/common/bits;
    
        location ^~ /site/secure/ {
            return 301 https://$host$request_uri;
        }
    }
    
    server {
        listen 443 ssl;
        ssl_certificate /etc/nginx/ssl/nginx.crt;
        ssl_certificate_key /etc/nginx/ssl/nginx.key;
    
        include /path/to/common/bits;
    }
    

    【讨论】:

    • 感谢您的回复。但是我有read,最好返回 307 状态码,因为它保留了请求类型。
    • 一个有效的考虑。但这也取决于应用程序。您可能希望 POST 到 http 失败,以避免掩盖严重的错误。
    • 我在实施当前解决方案时遇到问题。当我通过 http 向/site/secure/ 发送请求时,我有请求标头Content-Type:application/json;charset=UTF-8。但是当它被重定向到 https 请求时没有Content-Type,所以我从服务器收到错误。您知道在重定向到 https 期间如何保留 Content-Type 吗?感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 2010-09-27
    • 2017-07-15
    • 2019-11-17
    • 2017-05-05
    • 1970-01-01
    相关资源
    最近更新 更多