uwsgi啟動django應用 https訪問設置問題解決 & uwsgi: unrecognized option '--https' | ubuntu20.04


一般情況下,用uwsgi啟動django項目,我們很多用http啟動服務,也存在用https啟動服務,本文介紹uwsgi設置https啟動django項目。

總體來說,分以下幾步:

  • 生成 key & crt 文件
  • 啟動設置

1.生成key和crt文件

了解內容

# openssl genrsa
用於生成RSA私鑰,不會生成公鑰,因為公鑰提取自私鑰

# openssl req
根據私鑰生成一個新的證書請求文件

# openssl x509
簽署證書請求,生成證書,自簽署證書,往往是通過req生成請求文件,在x509簽署證書

通過openssl生成秘鑰key和證書crt

生成key & crt

# 生成rsa秘鑰,2048位
openssl genrsa -out foobar.key 2048

# 生成證書請求
openssl req -new -key foobar.key -out foobar.csr
# 具體交互見博主博文介紹openssl
# https://www.cnblogs.com/davis12/p/14410920.html

# 自行簽署,輸入證書請求,秘鑰簽名,輸出證書,有效期:10年(自己設置)
openssl x509 -req -days 3650 -in foobar.csr -signkey foobar.key -out foobar.crt

2.uwsgi設置

分兩種設置,一種是直接命令行的,另外一種就是通過ini文件設置。

2.1 命令行設置

uwsgi --master --https 0.0.0.0:8443,/root/test/ssl/foobar.crt,/root/test/ssl/foobar.key -w ./wsgi.py
# --master 設置主進程,默認1個worker

# --https 0.0.0.0:8443,/root/test/ssl/foobar.crt,/root/test/ssl/foobar.key 如果root用戶,可以設置8443端口,指明路徑下的證書和私鑰,
# 第四個參數省略,詳見博主博文介紹uwsgi的設置的
# https://www.cnblogs.com/davis12/p/14411643.html

# -w ./wsgi.py 指明wsgi文件路徑,根據自己路徑設置

uwsgi起來后:

2.2 ini文件設置

新建一個.ini文件,如uwsgi.ini,其中 https 項:

https = 0.0.0.0:8443,/root/test/ssl/foobar.crt,/root/test/ssl/foobar.key

啟動命令:

uwsgi --ini uwsgi.ini

3.問題匯總

我用ini方式啟動django項目后,編了個hello的視圖函數做測試,

curl -k  https://127.0.0.1:8443/hello
# -k 關閉證書驗證

報錯:

Internal Server Error

查閱資料后,應該是ini文件配置問題:

# 更正后的uwsgi.ini,主要是指定chdir 和 wsgi-file

[uwsgi]

https = 0.0.0.0:8443,/root/test/ssl/foobar.crt,/root/test/ssl/foobar.key

chdir = /root/test/django_test

wsgi-file = django_test/wsgi.py

master = true

pidfile = /var/run/xxx.pid 
# 通過pid停止重啟服務

daemonnize = true
# 守護進程,后台運行

再用curl測試:

curl -k  https://127.0.0.1:8443/hello

# 測試結果,正常
hello, django https

啟動 | 停止 | 重啟 uwsgi服務

# 啟動服務
uwsgi --ini xxx.ini

# 停止服務
uwsgi --stop /var/run/xxx.pid

# 重啟服務
uwsgi --reload /var/run/xxx.pid

啟動uwsgi出現no internal routing support, rebuild with pcre support
使用如下命令,記錄下,方便后人
需要注意的是pip install uwsgi 要加上–no-cache-dir,pip 可以強制下載重新編譯安裝的庫,不然pip會直接從緩存中拿出了上次編譯后的 uwsgi 文件,並沒有重新編譯一份。

ubuntu環境下

pip uninstall uwsgi

sudo apt-get install libpcre3 libpcre3-dev

pip install uwsgi --no-cache-dir

centos環境下

pip uninstall uwsgi
yum install -y pcre pcre-devel pcre-static
pip install uwsgi --no-cache-dir

4.arm架構機器uwsgi 啟動https服務出錯問題解決 & ubuntu 20.04同問題

最近遇到個很奇葩的問題,我用 amd64 平台的機器用 uwsgi 啟動 httpsdjango 是可以運行的,然而換成 arm64-arch 的一直報錯。

x86_64 啟動正常,處理請求正常:

aarch64 啟動異常,命令行和 ini 文件都不行:

於是google,別問為什么,因為百度出來的竟然還是自己的博文。

終於google上找到一篇博文的解決方案,基本描述如下:

# root用戶下
apt-get install libssl-dev
pip install uwsgi -I --no-cache-dir

其實這個問答的提問者遇到的問題和我用命令行啟動的一樣,回答的只是說很有可能需要重新編譯下uwsgi,但是,為什么呢?我不知道,可能真的平台架構不一樣吧,arm架構的服務器運行http還是沒有問題的,但https竟然報錯,而x86_64的服務器上,確實不管http還是https都沒有問題。

下面看我實際操作吧。

總之問題確實解決了。

遇到問題,根據提示一步步來吧,看提示,網上很多問題解答,很多並不能解決自己的問題,還是要自己動手解決。


免責聲明!

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



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