benwk
benwk
CDCloudflare Developers
Created by benwk on 9/4/2023 in #pages-help
How to setup Redirects for SPA with multiple directories?
Hi there. I have recently migrated an Angular application (SPA) to Cloudflare Pages. - Project: stream-portal.pages.dev - Deployment: e177e4f8.stream-portal.pages.dev - Account ID: b68c8e0fb165972eae029b7998838ca9 The application was previously hosted using Nginx and supports multiple languages, which is why its build directory is structured as follows:
/
├── dist/
│ └── en-us
│ └── fr-ca
│ └── zh-cn
/
├── dist/
│ └── en-us
│ └── fr-ca
│ └── zh-cn
In Nginx, I had set up proxy rules to accommodate the multi-directory structure:
server {
listen 80;
server_name localhost;

if ($accept_language ~ "^$") {
set $accept_language "en-us";
}

rewrite ^/$ /$accept_language permanent;

location ~ ^/(zh-cn|fr-ca|en-us) {
alias /app/;
index index.html;
try_files $uri /$1/index.html?$args;
}
}
server {
listen 80;
server_name localhost;

if ($accept_language ~ "^$") {
set $accept_language "en-us";
}

rewrite ^/$ /$accept_language permanent;

location ~ ^/(zh-cn|fr-ca|en-us) {
alias /app/;
index index.html;
try_files $uri /$1/index.html?$args;
}
}
Everything worked well with this setup. However, after migrating to Cloudflare Pages, I have encountered some routing issues. Specifically: - Navigation to https://funds.benwk.app/en-us/ works as expected because index.html is located under /en-us/. - Direct navigation (without accessing the first one, better in an Incognito Window) to https://funds.benwk.app/en-us/auth/sign-in returns a 404 error. I understand that this is likely due to the absence of rewrite or try_files rules similar to those in my Nginx setup. So I attempted to configure a _redirects file to achieve the same result:
/en-us/* /en-us/index.html 200
/en-us/* /en-us/index.html 200
Although I can see this redirect rule in the Deployment details, direct navigation to any /en-us/xxx route (e.g., https://funds.benwk.app/en-us/auth/sign-in) still returns a 404 error. My question is: How should I handle route rewrite for an Angular SPA with a multi-directory structure? Can the _redirects file suffice, or is there another way to accomplish this? Many thanks. Best, Ben
4 replies