Issue
I have a webapp built on NodeJS + Express / AngularJS.
AngularJS $routeProvider
is in html5
mode, meaning there is no index.html nor # in the URL.
I would like to use nginx to :
- proxy
/api
to my NodeJS app - redirect all request in
/
to/index.html
- redirect all request in
/app
to/app/index.html
Examples
/support
:/
should be rewrited toindex.html
, then the angular $routeProvider process thesupport
route and renderSupportController
/app/login
:/app/
should be rewrited to/app/index.html
, then the angular $routeProvider process thelogin
route and renderLoginController
/api/auth/login
:/api/*
should always be proxy redirected tohttp://localhost:3000/
cause there’s no static file to serve under/api
Constraint
The problem is, that using something like this to redirect to the API:
location / {
try_files $uri @backend;
}
Is not compatible with the AngularJS index.html rewrite:
location / {
try_files $uri $uri/ /index.html =404;
}
location /app/ {
try_files $uri $uri/ /app/index.html =404;
}
And if I specify a /api
location, Nginx overwrite it with the /
location …
What can I do here ?
Solution
I found the right configuration, I think I tested it before posting here but as nginx was redirecting https://example.com/api/login/auth
on http://locahost:3000/api/login/auth
and not http://locahost:3000/login/auth
, I was getting 404s from Express, so I thought they came from Nginx … I’m just "stupid as stupid does" …
Thanks for your help Tarun !
Here is the good configuration (which is really basic):
location /api {
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;
# Fix the "It appears that your reverse proxy set up is broken" error.
proxy_pass http://localhost:3000;
proxy_read_timeout 90;
proxy_redirect http://localhost:3000 https://example.com/api/;
}
location / {
try_files \$uri \$uri/ /index.html =404;
}
location /app/ {
try_files \$uri \$uri/ /app/index.html =404;
}
Answered By – Pierre C.
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0