Hak*_*kim 10 routes nginx angular
我正在为angular同一个server街区提供多个应用程序Nginx.因此,为了让用户直接浏览Angular我声明的某些自定义路线而不必通过主页(并避免404页面),我将这些路由从nginx转发到每个角度应用程序index.html,我添加了a try_files到每个location:
server {
listen 80;
server_name website.com;
# project1
location / {
alias /home/hakim/project1/dist/;
try_files $uri /index.html;
}
# project2
location /project2/ {
alias /home/hakim/project2/dist/;
try_files $uri /index.html;
}
# project3
location /project3/ {
alias /home/hakim/project3/dist/;
try_files $uri /index.html;
}
}
Run Code Online (Sandbox Code Playgroud)
这个解决方案在转到Angular路由时避免了404错误,但问题是当我浏览/project2/或/project3/重定向到/project1/.这显然不是预期的,因为我希望每个位置都转发到/project-i/index.html适当的项目.
在单个域上拥有多个独立应用程序通常是一种不好的安全实践。
然而,我相信你在这里面临的是工作方式的特殊性try_files——根据http://nginx.org/r/try_files,
如果未找到任何文件,则会内部重定向到最后一个参数中指定的 uri。
实际上,这意味着如果您的规范之后有一个额外的参数/index.html(即基本上任何东西),那么您的代码就会按您的预期工作;然而,由于缺少任何这样的最终参数,在每种情况下发生的情况都是所有内容都被重定向回/ location,就好像GET /index.html HTTP/1.1已经发出了请求一样(除非这一切都是在 nginx 内部完成的)。
因此,作为解决方案,您可以修复内部重定向的路径以保持相同location(例如,/projectX/index.html),或者保留路径,但使最后一个参数返回错误代码(例如,=404,永远不应该触发只要您的文件始终存在)。
例如try_files $uri /projectX/index.html;,,
或者,try_files $uri /index.html =404;。
如:
location /projectX/ {
alias /home/projectX/dist/;
try_files $uri /projectX/index.html; # last param is internal redirect
}
Run Code Online (Sandbox Code Playgroud)
或者:
location /projectX/ {
alias /home/projectX/dist/;
try_files $uri /index.html =404;
}
Run Code Online (Sandbox Code Playgroud)
总之,请注意,它/projectX/index.html只能作为最后一个参数,并且/index.html只能作为非最终参数。
希望这可以帮助某人
第1步 -构建所有项目
ng build --prod --base-href /project1/
ng build --prod --base-href /project2/
ng build --prod --base-href /project3/
Run Code Online (Sandbox Code Playgroud)
第2步 -配置您的Nginx,注意在try_files部分中添加的更改
server {
listen 80;
server_name website.com;
# project1
location / {
alias /home/hakim/project1/dist/;
try_files $uri/ /project1/index.html;
}
# project2
location /project2/ {
alias /home/hakim/project2/dist/;
try_files $uri/ /project2/index.html;
}
# project3
location /project3/ {
alias /home/hakim/project3/dist/;
try_files $uri/ /project3/index.html;
}
}
Run Code Online (Sandbox Code Playgroud)
第3步 -重新加载nginx配置
sudo service nginx reload
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5236 次 |
| 最近记录: |