程式架構:
+--------+ https +-------+ http +-------------+ | Client | ------> | Nginx | ------> | Spring Boot | +--------+ +-------+ +-------------+
Spring Boot轉導程式如下:
@GetMapping("/book")
public String book(@RequestParam Map<String, String> parameters, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("bookId", "00001");
return "redirect:/content";
}
用戶端連線https://x.x.x/book時,預期redirect至https://x.x.x/content
但實測時發現,轉導過程中會連線到http://x.x.x/content,應該是因為Spring Boot接收請求時,是http協定,所以預設會將redirect網址使用http協定連線。
為解決此問題,要在兩個地方做設定:
1.Nginx的nginx.conf
X-Forwarded-Proto要設定為https
location /book {
proxy_pass http://192.168.1.100:8888/book;
proxy_set_header Forwarded $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
2.Spring Boot程式的application.yaml
設定forward-headers-strategy:native、redirect-context-root:false
server:
forward-headers-strategy: native
tomcat:
redirect-context-root: false