樹莓派/Debian HTTP 到 HTTPS 端口重定向


一、前言

前文我們講了 樹莓派/Debian Apache2 配置自建 CA 實現 HTTPS(SSL) 服務 ,實現了通過 SSL 建立安全連接,但依然可以通過 HTTP 訪問。本文講述如何將 Raspberry/Debian HTTP 默認的 80 端口,重定向到 HTTPS 的 443 端口。

二、修改 HTTP 配置文件 000-default.conf

1. 開始編輯 000-default.conf

sudo vim /etc/apache2/sites-available/000-default.conf

2. 添加語句

在任意一處添加語句:

ServerName example.com
ServerAlias www.example.com

Redirect permanent / https://example.com/
  • 如果沒有申請域名,可替換為 IP 地址:

    ServerName 192.168.0.130
    ServerAlias 192.168.0.130
    
    Redirect permanent / https://192.168.0.130/
    
    • 如果替換的 IP 地址是公網 IP ,不會影響。
    • 如果替換的 IP 地址是本地 IP ,則只能由同一網段內的 計算機 訪問。(比如我用到的 192.168.0.130)

3. :wq 保存退出

三、修改 HTTPS 配置文件 default-ssl.conf

1. 開始編輯 000-default.conf

sudo vim /etc/apache2/sites-available/default-ssl.conf

2. 修改語句

修改 ServerName 后面的字符串為 域名

ServerName example.com
  • 如果沒有申請域名,可替換為 IP 地址,例:

    ServerName 192.168.0.130
    

2. 添加語句

ServerName 語句后添加語句:

ServerAlias www.example.com

Protocols h2 http:/1.1
  • 如果沒有申請域名,可替換為 IP 地址:

    ServerAlias 192.168.0.130
    
    Protocols h2 http:/1.1
    
    • 如果替換的 IP 地址是公網 IP ,不會影響。
    • 如果替換的 IP 地址是本地 IP ,則只能由同一網段內的 計算機 訪問。(比如我用到的 192.168.0.130)

使用上述配置,我們將強制使用 HTTPS 。

四、 重新加載Apache服務以使更改生效

sudo systemctl reload apache2
sudo /etc/init.d/apache2 restart

五、成功測試

完成上述步驟且無錯誤后,打開瀏覽器輸入:

http://<域名或IP>

就會跳轉到:

https://<域名或IP>

六、HTTPS 實現 www 重定向到 非www 網頁

請參考博客 HTTPS 實現 www 重定向到 非www 網頁


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM