Nginx block server routing

2019-09-08 10:35发布

问题:

I am trying to route a url to another part of my server - the admin area which is made by angular using nginx server blocks.

I can get it working using

location ~ /admin {
     root /home/sysadmin/html;
}

This routes to /home/sysadmin/html/admin.index.html. What I can't figure out is how to route all deeper URLS to this file location i.e. /admin/dashboard/ would also go to /home/sysadmin/html/index.html.

For example, if go to www.url.com/admin/ it works and my angular app runs but if I refresh on www.url.com/admin/login it will produce a 404.

I need all child urls of /admin to go to my systems /home/sysadmin/html/admin/index.html file.

Please note, this is a nginx issue not a angular one as I can navigate and run my project fine.

is it best to setup an alternative subdomain that points to www.url.com/admin and manage it another server block?

Hope this is clear.

回答1:

What you are looking for is the Nginx try_files directive.

location ~ /admin { root /home/sysadmin/html/admin; try_files $uri $uri/ /index.html =404; }

This says that it will test for the existence of the actual files or folders (relative to the root folder you specified) first, and then if none are found it will return the index.html in that root instead.

This is common when setting up HTML5 mode in Angular, for which it sounds like you are trying to do.



回答2:

You need to define a .htaccess file and make a rewrite base

 # If the request is a file, folder or symlink that exists, serve it up
 RewriteCond %{REQUEST_FILENAME} -s [OR]
 RewriteCond %{REQUEST_FILENAME} -l [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^(.+)$ - [S=1]

 # otherwise, serve your index.html app
 RewriteRule ^(.+)$ /index.html

you need also config in angularJS depending ngroute or ui.router

 // use the HTML5 History API
 $locationProvider.html5Mode(true);

and put also a meta in head like this

<base href="/someappfolder/">

update: I should add this for nginx configuration

  # nginx configuration
  location / {
  if (-e $request_filename){
  rewrite ^(.+)$ /index.html;
  }
  }

also take a look at here http://senior-java-developer.com/html5angularjsnginx-crawlable-application/