Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...