I have one NGINX server (nginx1) that should proxy all requests to NGINX server (nginx2) running Angular2 app. Only requests to /api should be sent to a asp.net core server (nginx3). Follow the nginx1 configuration below:
server { # should proxy all requests to nginx2 and /api to nginx3
listen 80;
server_name mywebsite.com;
location / {
proxy_set_header Host $host;
proxy_pass http://mywebsite.com:4999/;
}
# proxy para o backend
location /api {
proxy_pass http://mywebsite.com:5001;
proxy_set_header Host $host;
}
}
Follow the nginx2 configuration below:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 4999;
server_name 'mywebsite.com';
location / {
root /usr/share/nginx/html;
try_files $uri$args $uri$args/ index.html;
}
#error_page 404 /error.html;
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
If I attempt to open mywebsite.com, it opens correctly, but If I type the complete angular2 route (ex: http://mywebsite.com/orders ), I get error 404 from nginx1.
What am I missing?
I don't think your problem is with your proxy, it is with your NGINX2. On this server, the folder /orders doesn't exist and will return a 404 to the proxy NGINX1 - which will just return that to the caller. In order for this to work, you'd have to add rewrite rules to NGINX2 that rewrites everthing that is not a file or a folder to your main angular2 index.html file.
It seems to be related to Angular2 router. I added the following lines to my app.module.ts (running under nginx2):
import {HashLocationStrategy, LocationStrategy} from "@angular/common";
providers: [
{provide: LocationStrategy, useClass: HashLocationStrategy },
...
]
Now, it works perfectly whenever I type a complete url like http://mywebsite.com/#/orders or refresh any page.
I still think this is not the best solution, since every path now is prefixed with '#', but at least it works. :-)
More info about angular2 HashLocationStrategy at: https://angular.io/docs/ts/latest/guide/router.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.