我正在嘗試通過 Nginx 服務器在 Gunicorn 上運行 Flask 應用程式。如果可能的話,我希望應用程式在子目錄上運行,而不是通過不同的埠,但我得到的只是 404 錯誤。這是我的 conf 檔案,它是 conf.d 檔案夾中的一個包含檔案:
server {
listen 80;
server_name 127.0.0.1;
location / {
root /var/www/html;
}
location /chess/ {
proxy_pass http://unix:/usr/share/nginx/sockets/chess.sock;
proxy_set_header Host $http_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 $scheme;
}
}
有人可以告訴我該怎么做嗎?我已經看了一遍,嘗試了很多不同的東西,但無濟于事。它在不同的埠上運行良好,但這不是我想要的。子域也是一個合適的選擇,但出于某種原因,我只能讓它在生產中作業,而不是在開發中作業。
myproject.py:
from flask import Flask
app = Flask(__name__)
@app.route("/chess/",defaults={'name': None})
@app.route("/chess/<name>")
def hello(name):
if name is None:
name="!"
else:
name = ", " name
# PLEASE don't use the following line of code in a real app, it creates a self-xss vulnerability. ALWAYS sanitize user input.
return f"<h1 style='color:blue'>Hello There{name}</h1>"
if __name__ == "__main__":
app.run(host='0.0.0.0')
nginx - /etc/nginx/sites-enabled/myproject (symlink)
server {
listen 8080;
server_name your_domain www.your_domain;
location / {
root /home/username/myproject/static/;
}
location /chess/ {
include proxy_params;
proxy_pass http://unix:/home/username/myproject/myproject.sock;
}
}
<host>:8080/chess/stackoverflow:

<host>:8080/a.html: (實際上是從/home/myproject/static)

一般和將來參考 - 嘗試查看 nginx 日志(/var/log/nginx)或服務日志(journalctl -u myproject或systemctl status myproject)
uj5u.com熱心網友回復:
進一步的研究表明,無論如何,不??建議在埠 80 上運行 Gunicorn,而是應該proxy_pass像這樣在 NGINX 上運行另一個:
server {
listen localhost:80;
location / {
root /var/www/html;
}
location /chess/ {
proxy_pass http://localhost:8080/;
}
}
server {
listen localhost:8080;
location / {
proxy_pass http://unix:/usr/share/nginx/sockets/chess.sock;
proxy_set_header Host $http_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 $scheme;
}
}
需要注意的是,該proxy_pass http://localhost:8080/行中的最后一個斜杠對于避免 404 錯誤是必要的。不需要更改 Flask 應用程式代碼。使用此設定,兩者都localhost/chess定向localhost:8080到 Flask 應用程式,同時localhost定向到原始 HTML 根目錄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520784.html
