nginx 提供静态 html 和代理
Posted
技术标签:
【中文标题】nginx 提供静态 html 和代理【英文标题】:nginx serve static html and proxy 【发布时间】:2020-03-26 18:55:04 【问题描述】:我在 Digital Ocean 上有一个 droplet,我用它来托管一个网站和该网站的 API。
我想要:
https://example.com为网站服务 https://example.com/api 提供 API,在端口 3000 上运行。这是我的/etc/nginx/nginx.conf
文件:
http
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/http-error.log;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server
server_name example.com; # managed by Certbot
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
# SSL settings
ssl_certificate /path/to/file.pem; # managed by Certbot
ssl_certificate_key /path/to/file.pem; # managed by Certbot
include /path/to/file.conf; # managed by Certbot
ssl_dhparam /path/to/file.pem; # managed by Certbot
proxy_http_version 1.1;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_cache_bypass $http_upgrade;
proxy_redirect off;
# Routes
location /api/
proxy_pass http://127.0.0.1:3000/;
location /
root /usr/share/nginx/html;
error_page 404 /404.html;
location = /40x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html
server
if ($host = example.com)
return 301 https://$host$request_uri;
# managed by Certbot
listen 80 ;
listen [::]:80 ;
server_name example.com;
return 404; # managed by Certbot
提供静态 html 文件效果很好,但 https://example.com/api/ 返回 502: Bad Gateway
错误。我不明白我做错了什么......任何帮助将不胜感激。谢谢。
【问题讨论】:
【参考方案1】:原来我的配置完全没问题。我只需要在 Droplet 上启用网络。我使用this post 这样做。谢谢大家!
简而言之:
setsebool httpd_can_network_connect on
【讨论】:
【参考方案2】:location /
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:3000;
这通常不会让我失望。请尝试。
【讨论】:
这些标头已经设置在 server 指令下,proxy_pass
设置在 location /api/
指令下。我希望 /
提供上面目录中的静态 html。谢谢。以上是关于nginx 提供静态 html 和代理的主要内容,如果未能解决你的问题,请参考以下文章