Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect all Angular request to index.html in Nginx

Tags:

I have create a simple Nginx config file to server an Angular like so:

server {   listen 80;   listen [::]:80;    root /path/to/apps/myapp/current/dist;   access_log /path/to/apps/myapp/current/log/nginx.access.log;   error_log /path/to/apps/myapp/current/log/nginx.error.log info;    index index.html;    location ^~ /assets/ {     gzip_static on;     expires max;     add_header Cache-Control public;   }    location / {     try_files $uri $uri/ =404;   } } 

And all works fine as expected. because I'm using Angular UI Router, I'd like to forward all pages to index.html so Angular will take over (so a request to example.com/users/new will be redirect by Nginx to index.html, for Angular UI to handle it) for pages reloads, links, etc.

How can I achieve this?

I've playing around with options like:

server {     #implemented by default, change if you need different ip or port     #listen *:80 | *:8000;     server_name test.com;     return 301 $scheme://www.test.com$request_uri; } 

As specified in this answer. But I couldn't anything similar to work based on all requests.

Suggestions will be much appreciated.

like image 417
WagnerMatosUK Avatar asked Jan 27 '16 13:01

WagnerMatosUK


1 Answers

You need to add the router to the end of your try_files directive, like this:

location / {     try_files $uri $uri/ /index.html; } 

See this document for more.

like image 55
Richard Smith Avatar answered Sep 20 '22 12:09

Richard Smith