Cloudflare redirect - CSS, Images, JS not working after redirect
Hi, I have written a website in Astro that is hosted on Cloudflare Pages. I have written redirect rules related to cookie values and country the visitors is from. The redirect itself works great. But it breaks the site's CSS, JS and image links. Is there a way to make the redirects work and not break the site?
These are the redirect rules:
If Expression
and Then Expression Dynamic
`
and status code 302
And the other one has the If expression
Would be grateful for your help
6 Replies
Nobody can help?
Nobody at all.
In seriousness, it's because the redirect is somehow capturing resources your site depends on.
Usually with a multi-language site you would go about this differently, either
A: Only doing the redirect on the root page
B: Doing the redirect via Javascript
C: Having each country specific path or subdomain only rely on resources from that country specific path/subdomain
D: Doing the redirect in a page-aware fashion server-side or client-side, like doing it in the actual application which knows what is a page which should be redirected instead of a resource
Like using Astro's interalization directly: https://docs.astro.build/en/recipes/i18n/ and then having it query for their country (you could make an server-side endpoint which returns request.cf.country) in the client-side code and redirect itself if nothing is forced
Astro Documentation
Add i18n features
Use dynamic routing and content collections to add internationalization support to your Astro site.
If you really want to stick with using a CF Redirect Rule, you'd have to configure it to ignore the assets it depends on. Could add
and not http.request.uri.path.extension in {"js" "css" "json" "png" "jpeg" "jpg" "gif" "webp"}
to the end of it and try to get it to not redirect those resources. It's just a bit more hacky/not doing it properly imo, but it may be easier. If you go that route and it still doesn't work, open up dev tools ctrl+shift+i -> Network and look for requests to assets which are getting redirect (301/302) responses and whitelist their extensionsThanks, this is very helpful. I did set up a redirect language switched in Astro itself. This is the one that sets the cookie. My hope was that this cookie would be recognised and then redirect automatically if they visit again, to avoid confusion when they land on the locale they don't understand when they revisit.
I will try to find a solution that works with your tips. Thanks again
hmm yea language specific stuff is interesting and hard to get right. Any reason why you couldn't have Astro check for if the cookie is set and redirect if is on the wrong page? Would elimate one of those redirects
I am currently using it as SSG on cloudflare pages. I would assume this requires SSR? Maybe I could have an event on initial page load but then it would first load the page in German and then redirect to English as a second step, if I'm not mistaken.