Open Source How-To

You are here: Home > 4. Ubuntu 18.04 Server > การตั้งค่า haproxy สำหรับ redirect http เป็น https

การตั้งค่า haproxy สำหรับ redirect http เป็น https

 
 

บันทึกนี้ปรับปรุงล่าสุดเมื่อวันที่ 5-10-2561
ดูแลโดย WIBOON

  • เป็นเรื่องราวที่ทำเพิ่มหลังจากที่ได้ทำเรื่อง ติดตั้ง haproxy บน ubuntu 18.04 server มาก่อนแล้ว
  • โดยการเพิ่มบรรทัดข้างล่างนี้ที่ section backend
    redirect scheme https if !{ ssl_fc }


ขั้นตอนดังนี้
1. แก้ไขไฟล์ haproxy.cfg ด้วยเอดิเตอร์ vi หรือ nano ก็ได้

sudo nano /etc/haproxy/haproxy.cfg

เพิ่มบรรทัดข้างล่างนี้ แทนแบบเดิมที่บริการทั้ง http และ https

# use only https (redirect http to https)
frontend www-http
   bind *:80
   mode http
   acl host_tblog1 hdr_beg(host) -i tblog1
   use_backend tblog1-backend if host_tblog1
frontend www-https
   bind *:443 ssl crt /etc/ssl/private/my.pem
   mode http
   acl host_tblog1 hdr_beg(host) -i tblog1
   use_backend tblog1-backend if host_tblog1
backend tblog1-backend
   option forwardfor
   http-request set-header X-Forwarded-Port %[dst_port]
   http-request add-header X-Forwarded-Proto https if { ssl_fc }
   redirect scheme https if !{ ssl_fc }
   server tblog1 10.25.51.155:80

2. รีสตาร์ท haproxy

sudo systemctl restart haproxy.service 
sudo systemctl status haproxy.service
tail -f /var/log/haproxy.log 

3. ทดสอบ
เข้า browser เพื่อไปยัง http://tblog1.example.com
เข้า browser เพื่อไปยัง https://tblog1.example.com


ตัวอย่างตั้งค่า haproxy สำหรับ redirect http เป็น https ทั้ง tblog1 และ tblog2

sudo nano /etc/haproxy/haproxy.cfg

แก้ไขให้ได้ตามนี้

# use only https (redirect http to https)
frontend www-http
   bind *:80
   mode http
   acl host_tblog1 hdr_beg(host) -i tblog1
   use_backend tblog1-backend if host_tblog1
   acl host_tblog2 hdr_beg(host) -i tblog2
   use_backend tblog2-backend if host_tblog2
frontend www-https
   bind *:443 ssl crt /etc/ssl/private/my.pem
   mode http
   acl host_tblog1 hdr_beg(host) -i tblog1
   use_backend tblog1-backend if host_tblog1
   acl host_tblog2 hdr_beg(host) -i tblog2
   use_backend tblog2-backend if host_tblog2
backend tblog1-backend
   option forwardfor
   http-request set-header X-Forwarded-Port %[dst_port]
   http-request add-header X-Forwarded-Proto https if { ssl_fc }
   redirect scheme https if !{ ssl_fc }
   server tblog1 10.25.51.155:80
backend tblog2-backend
   option forwardfor
   http-request set-header X-Forwarded-Port %[dst_port]
   http-request add-header X-Forwarded-Proto https if { ssl_fc }
   redirect scheme https if !{ ssl_fc }
   server tblog2 10.25.51.245:80

-- Browser --
http://tblog1.example.com
http://tblog2.example.com
--

nach oben