# NGINX http 轉址 https 教程
# 簡介
Nginx 是 Linux 上最熱門的網頁伺服器,除了可以建設網頁服務以外,代理的功能也被廣泛使用,本教程主要就是通過代理的方式,來把原本只有 http 的服務,套上 https 加強傳輸安全性
本教程需根據使用環境做調整
本教程使用docker環境
# 建立 docker-compose.yml
| version: "3.9" |
| service: |
| nginx: |
| container_name: proxy |
| image: nginx:latest |
| restart: always |
| stdin_open: true |
| tty: true |
| network_mode: host |
| volume: |
| - nginx_data:/etc/nginx |
| volumes: |
| nginx_data: |
| external: true |
# 建立 volume
| docker volume create nginx_data |
# 啟動 docker
# 編輯設定檔
| cd $(docker volume inspect --format '{{ .Mountpoint }}' nginx_data) |
| cd conf.d |
| vim default.conf |
default.conf | server { |
| listen 80; |
| server_name www.domain.com; |
| return 301 https://$server_name$request_uri; |
| } |
| server { |
| listen 443 ssl; |
| |
| server_name www.domain.com; |
| ssl_certificate /etc/nginx/conf.d/cert.crt; |
| ssl_certificate_key /etc/nginx/conf.d/cert.key; |
| |
| location / { |
| proxy_pass http://192.168.X.X:8081; |
| proxy_set_header Host $host; |
| proxy_set_header X-Real-IP $remote_addr; |
| proxy_set_header X-Forwarded-Proto https; |
| } |
| |
| error_page 500 502 503 504 /50x.html; |
| location = /50x.html { |
| root /usr/share/nginx/html; |
| } |
| } |
# 上傳憑證
| cp /path/to/cert.crt $(docker volume inspect --format '{{ .Mountpoint }}' nginx_data)/conf.d/ |
| cp /path/to/cert.key $(docker volume inspect --format '{{ .Mountpoint }}' nginx_data)/conf.d/ |
# 重啟 Nginx
| docker-compose down |
| docker-compose up -d |