[英]Hosting static angular2 app on nginx and proxying http requests to backend api
如何讓angular2路由工作並將http請求代理到另一台機器上的rest api?
我在nginx服務器上有一個angular2 web應用程序,它提供靜態html文件。 我在另一台具有不同IP地址的計算機上托管了一個單獨的rest api。 我已將位置設置為/在我的nginx配置文件中,以允許angular2路由正常工作。 我還添加了一個位置/ api /我希望攔截任何api請求並將它們代理到我的后端api。
我的nginx conf代理設置為http://swapi.co用於測試目的。
events {
worker_connections 4096; ## Default: 1024
}
http {
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html index.htm;
include /etc/nginx/mime.types;
location / {
# If you want to enable html5Mode(true) in your angularjs app for pretty URL
# then all request for your angularJS app will be through index.html
try_files $uri /index.html;
}
# /api will server your proxied API that is running on same machine different port
# or another machine. So you can protect your API endpoint not get hit by public directly
location /api/ {
proxy_pass http://swapi.co;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#Static File Caching. All static files with the following extension will be cached for 1 day
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1d;
}
}
}
我的angular2服務
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class Service {
private url: string = '/api/people/';
constructor (private http: Http) {}
getPeople () {
return this.http.get(this.url)
.map(res => res.json());
}
}
任何幫助將非常感激。
得到它在我的開發環境中正確代理請求。 添加到http塊並指向代理傳遞給上游api值
upstream api {
server 192.168.0.15:9998;
}
完整配置:
events {
worker_connections 4096; ## Default: 1024
}
http {
# Change this depending on environment
upstream api {
server 192.168.0.1:9998;
}
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html index.htm;
include /etc/nginx/mime.types;
location / {
# If you want to enable html5Mode(true) in your angularjs app for pretty URL
# then all request for your angularJS app will be through index.html
try_files $uri /index.html;
}
# /api will server your proxied API that is running on same machine different port
# or another machine. So you can protect your API endpoint not get hit by public directly
location /api {
proxy_pass http://api;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#Static File Caching. All static files with the following extension will be cached for 1 day
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1d;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.