MEAN应用子域名部署时API请求路由至Node服务器的配置问题
Fixing NGINX Routing for MEAN Stack API Requests
Got it, the issue here is that right now all requests to app.example.com are being routed to your Angular frontend (thanks to the try_files rule), including your API calls. We need to add a specific NGINX location block to catch API requests and forward them to your Node.js server running on port 8080.
Updated NGINX Configuration
Here's how to modify your server block to handle both frontend and backend traffic properly:
server { listen 80; listen [::]:80; server_name app.example.com; root /var/www/app/frontend/dist; index index.html; # Handle API requests - adjust the path if your API uses a different prefix location /api { proxy_pass http://localhost:8080; 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-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_cache_bypass $http_upgrade; } # Handle all other requests (Angular frontend routing) location / { try_files $uri $uri/ /index.html?$query_string; } }
Key Details to Note:
location /api: This block catches any request starting with/api(if your API uses a different prefix like/api/v1or/backend, just update this path to match).proxy_pass http://localhost:8080: Forwards the matched API requests directly to your Node.js server running on port 8080.- Proxy Headers: The
proxy_set_headerlines ensure your Node.js backend receives accurate details about the original request (like client IP, host, and protocol), which is critical for things like authentication or generating correct response URLs.
Next Steps to Apply Changes:
- Save your updated NGINX configuration file.
- First, test for syntax errors to avoid breaking your server:
sudo nginx -t - If the test passes, restart NGINX to activate the new routing rules:
sudo systemctl restart nginx - Now your Angular app's API requests (e.g.,
https://app.example.com/api/users) should be routed to the Node.js backend instead of timing out.
内容的提问来源于stack exchange,提问作者Anirudh
相关产品推荐
相关产品推荐

