Nginx

子域和代理伺服器的 nginx 配置

  • August 27, 2018

我在這裡嘗試了很多其他的文章解決方案,沒有人可以幫助我解決我的問題。我有一個簡單的 nginx 配置,帶有 https 和一個帶有主路徑的 node.js 應用程序,/而對於子域另一個路徑/api。我可以mywebapp.com正確訪問,但如果我嘗試訪問api.mywebapp.com它會將我重定向到“歡迎使用 nginx”頁面。我的 DNS 記錄api.mywebapp.com指向我的伺服器 IP 地址。

這是我的 nginx 配置塊:

server {
   listen 443 ssl http2;
   listen [::]:443 ssl http2;

   server_name mywebapp.com;

   # SSL
   include /etc/letsencrypt/mycerts.conf;
   include /etc/letsencrypt/options-ssl-nginx.conf;

   # reverse proxy
   location / {
       proxy_pass http://localhost:8000;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection 'upgrade';
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $remote_addr;
       proxy_cache_bypass $http_upgrade;
   }
}

server {
   listen 443 ssl http2;
   listen [::]:443 ssl http2;

   server_name api.mywebapp.com;

   # SSL 
   include /etc/letsencrypt/mycerts.conf;      
   include /etc/letsencrypt/options-ssl-nginx.conf;

   location /api {
       limit_req zone=mylimit;
       proxy_pass http://localhost:8000/api;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection 'upgrade';
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $remote_addr;
       proxy_cache_bypass $http_upgrade;
   }
}

我錯過了什麼?

您將代理配置為

location /api {
 # ...
}

所以它只能通過https://api.mywebapp.com/api/.

您很可能希望將其更改為

location / {
 proxy_pass http://localhost:8000/api;  # <- keep this
 # ...
}

引用自:https://serverfault.com/questions/928133