我目前在端口80上运行nginx,configuration的服务器名称为example.com和www.example.com 。
我也有一个Flask应用程序,我希望可以通过端口80访问,但使用主机名app.example.com 。
由于nginx已经在使用端口80,我怎样才能将app.example.com请求路由到Flask应用程序呢?
请注意,服务器只有一个IPv4地址。
应该相当容易。
确保Flask本身在80以外的端口上运行。
然后使用NginX作为反向代理(和web服务器)来处理app.example.com的子域名,然后将其作为localhost:8080(或任何你的瓶颈应用绑定的地方)的代理来处理。
upstream flask { server 127.0.0.1:8080; #Flask } server { listen YOUR_PUBLIC_IP:80; server_name app.example.com; location / { proxy_pass http://flask; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; proxy_redirect off; proxy_buffering off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
只要server_name不同,您可以在端口80上拥有许多服务器块,并像Apache VirtualHosts一样使用它们。
在端口80上直接服务应用程序并不是一个好主意。有一个标准的HTTP服务器侦听端口80并将请求转发到Python(Flask)应用程序的WSGI服务器要好得多。
您应该configurationnginx将app.example.com的所有请求发送到您的WSGI(Python应用程序服务器)。 这样, http://example.com: 80的请求将由nginx直接提供,虚拟主机app.example.com:80的所有请求都将被转发到您的Python应用服务器。 根据您的偏好,您可以使用uWSGI或gunicorn运行您的Python / Flask应用程序。
要将app.example.comconfiguration为虚拟主机,您将需要创build一个文件(例如,如果您使用的是基于Debian的发行版的/etc/nginx/sites-available/app.example.com ),它将包含类似这个:
server { server_name app.example.com; access_log /var/log/nginx/app-access.log; error_log /var/log/nginx/app-error.log; location /static { root /var/www/app.example.com/static; # adjust to fit your path here } location / { uwsgi_pass unix:/tmp/uwsgi_app.sock; include /etc/nginx/conf.d/uwsgi_params; } }
location /部分的内容需要调整,取决于您select使用的特定WSGI服务器 – 请参阅下文。
然后,您需要将新的虚拟主机configuration符号链接到启用了站点的站点,然后重新启动nginx:
ln -sf /etc/nginx/sites-available/app.example.com /etc/nginx/sites-enabled/ /etc/init.d/nginx restart
有关configurationnginx以在同一IP地址和TCP端口上为多个站点(虚拟主机)提供服务的更多信息,请参阅此文档。
下面是两篇博客文章,介绍如何使用uWSGIconfigurationnginx: 使用Nginx和uWSGI部署Flask使用nginx和uWSGI 设置Flask 。 如果你更喜欢gunicorn(Ruby的独angular兽应用服务器的Python WSGI端口),你可以检查这个问题: 使用nginx和gunicorn运行Flask应用程序,并 使用Nginx和gunicorn服务Flask应用程序