angular 前端路由不生效解決方案
Intro
最近使用 Angular 為我的活動室預(yù)約項目開發(fā)一個前后端分離的客戶端,在部署上遇到了一個問題,前端路由不生效,這里記錄一下。本地開發(fā)正常,但是部署到服務(wù)器上就有問題,之前部署到IIS上時需要配置一個 url rewrite ,可能遇到了類似的問題,查閱一番之后確實是這樣。
啟用前端路由服務(wù)器配置
沒有一種配置可以適用于所有服務(wù)器。 后面這些部分會描述對常見服務(wù)器的配置方式。 這個列表雖然不夠詳盡,但可以為你提供一個良好的起點。
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
-
NGinx:使用
try_files指向index.html,詳細(xì)描述見Web 應(yīng)用的前端控制器模式。
try_files $uri $uri/ /index.html;
<system.webServer>
<rewrite>
<rules>
<rule name="Angular Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
GitHub 頁面服務(wù):你沒辦法直接配置 Github 的頁面服務(wù),但可以添加一個 404 頁,只要把
index.html復(fù)制到404.html就可以了。 它仍然會給出一個 404 響應(yīng),但是瀏覽器將會正確處理該頁,并正常加載該應(yīng)用。 使用在主分支的docs/下啟動服務(wù) 并創(chuàng)建一個.nojekyll文件也是一個好辦法。
"rewrites": [ {
"source": "**",
"destination": "/index.html"
} ]
Docker 部署
我使用了 Docker 部署,最后部署在 nginx 下了,按上面的提示在 nginx 配置中配置 try file,修改 nginx 默認(rèn)配置文件如下:
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
在打包 docker 鏡像時替換默認(rèn)的 nginx 配置,Dockerfile 如下所示:
FROM node:12-alpine AS builder
# set working directory
WORKDIR /app
# install and cache app dependencies
COPY package.json .
RUN npm install
# build the angular app
COPY . .
RUN npm run build
FROM nginx:alpine
# copy from dist to nginx root dir
COPY --from=builder /app/dist/ReservationClient /usr/share/nginx/html
# expose port 80
EXPOSE 80
# set author info
LABEL maintainer="WeihanLi"
COPY ./conf/nginx.default.conf /etc/nginx/conf.d/default.conf
# run nginx in foreground
# https://stackoverflow.com/questions/18861300/how-to-run-nginx-within-a-docker-container-without-halting
CMD ["nginx", "-g", "daemon off;"]
按上面的 Dockerfile 打包之后前端路由就可以正常使用了~~
我的 angular 做的活動室預(yù)約客戶端體驗地址:https://reservation-preview.weihanli.xyz/