MENU

Nginx http强制跳转https的坑 (POST请求重定向到GET)

December 20, 2023 • Read: 235 • 学习·笔记

TL;DR
如果Nginx强制跳转使用的是301,浏览器或Postman将Post请求跳转后使用GET请求导致后端出错,Nginx调整为307即可

当配置好ssl,希望网站通过https请求,配置完成一般都会配置http跳转到https,网上找的代码一般如下

server {
    listen 80;
    listen [::]:80;
    server_name foo.example.com;

    # 将 HTTP 请求重定向至 HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name foo.example.com;
    include conf.d/foo.example.ssl.incl;
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://127.0.0.1:8080;
    }
}

在前端网页GET请求一切正常,如果是POST接口请求,如浏览器、Postman等客户端会自动请求跳转为HTTPS的GET请求,导致后端报错,常见错误为:请求的body丢失,方法不允许

此时只需要修改为:

server {
    listen 80;
    listen [::]:80;
    server_name foo.example.com;

    # 将 HTTP 请求重定向至 HTTPS
    return 307 https://$host$request_uri;
}

参考:
nginx-POST请求遇到301重定向的坑
POST请求慎用301 Moved Permanently


本文由 ONE 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
如有版权疑问交流,请给我留言:oneisall8955@gmail.com
本文永久链接:https://liuzhicong.cn/index.php/study/nginx-http-force-redirect-https-pit.html

Archives QR Code Tip
QR Code for this page
Tipping QR Code