angular 前端路由不生效解決方案
Intro
最近使用 Angular 為我的活動室預約項目開發一個前后端分離的客戶端,在部署上遇到了一個問題,前端路由不生效,這里記錄一下。本地開發正常,但是部署到服務器上就有問題,之前部署到IIS上時需要配置一個 url rewrite ,可能遇到了類似的問題,查閱一番之后確實是這樣。
啟用前端路由服務器配置
沒有一種配置可以適用於所有服務器。 后面這些部分會描述對常見服務器的配置方式。 這個列表雖然不夠詳盡,但可以為你提供一個良好的起點。
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
,詳細描述見Web 應用的前端控制器模式。
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 頁面服務:你沒辦法直接配置 Github 的頁面服務,但可以添加一個 404 頁,只要把
index.html
復制到404.html
就可以了。 它仍然會給出一個 404 響應,但是瀏覽器將會正確處理該頁,並正常加載該應用。 使用在主分支的docs/
下啟動服務 並創建一個.nojekyll
文件也是一個好辦法。 -
Firebase 主機服務:添加一條重寫規則。
"rewrites": [ {
"source": "**",
"destination": "/index.html"
} ]
Docker 部署
我使用了 Docker 部署,最后部署在 nginx 下了,按上面的提示在 nginx 配置中配置 try file
,修改 nginx 默認配置文件如下:
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 鏡像時替換默認的 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 做的活動室預約客戶端體驗地址:https://reservation-preview.weihanli.xyz/