There's a way using dynamic redirects powered by the inbuilt function app. Your staticwebapp.config.json
needs this:
"navigationFallback": {
"rewrite": "/api/fallback"
}
and a fallback
function to handle the redirect; something like this:
//@ts-check
const { parseURL } = require('ufo');
const routes = require('./redirects');
/**
*
* @param { import("@azure/functions").Context } context
* @param { import("@azure/functions").HttpRequest } req
*/
async function fallback(context, req) {
const originalUrl = req.headers['x-ms-original-url'];
if (originalUrl) {
// This URL has been proxied as there was no static file matching it.
context.log(`x-ms-original-url: ${originalUrl}`);
const parsedURL = parseURL(originalUrl);
const matchedRoute = routes.find((route) =>
parsedURL.pathname.includes(route.route)
);
if (matchedRoute) {
context.log(`Redirecting ${originalUrl} to ${matchedRoute.redirect}`);
context.res = {
status: matchedRoute.statusCode,
headers: { location: matchedRoute.redirect },
};
return;
}
}
context.log(
`No explicit redirect for ${originalUrl} so will redirect to 404`
);
context.res = {
status: 302,
headers: {
location: originalUrl
? `/404?originalUrl=${encodeURIComponent(originalUrl)}`
: '/404',
},
};
}
module.exports = fallback;
You get a lot of flexibility here to implement any solution you desire; including wildcards
There's a more in depth explanation here: https://johnnyreilly.com/2022/12/22/azure-static-web-apps-dynamic-redirects-azure-functions