Warm tip: This article is reproduced from serverfault.com, please click

How do I translate a .htaccess file to Firebase hosting config?

发布于 2020-11-29 14:26:46

I've built an SPA in Angular 2, and I'm hosting it on Firebase Hosting. I have built som extra static html pages specifically for crawl bots (since they do not read updated dynamic html, only the initial index.html) and now I need to rewrite the URL for HTTP requests from bots to these static pages.

I know how to do this in a .htaccess file, but I can't figure out how to translate the rewrite conditions in my firebase.json file.

This is my .htaccess:

RewriteEngine On
 
# Remove trailing /
RewriteRule ^(.*)/$ /$1 [L,R=301]
 
# Rewrite spiders to static html
RewriteCond %{HTTP_USER_AGENT} (googlebot|bingbot|msnbot|yahoo|Baidu|aolbuild|facebookexternalhit|iaskspider|DuckDuckBot|Applebot|Almaden|iarchive|archive.org_bot) [NC]
RewriteCond %{DOCUMENT_ROOT}/static%{REQUEST_URI}.html -f
RewriteRule ^(.*)$ /static/$1.html [L]
 
# Rewrite spiders to static index.html
RewriteCond %{HTTP_USER_AGENT} (googlebot|bingbot|msnbot|yahoo|Baidu|aolbuild|facebookexternalhit|iaskspider|DuckDuckBot|Applebot|Almaden|iarchive|archive.org_bot) [NC]
RewriteCond %{REQUEST_URI} "^/$"
RewriteRule ^ /static/index.html [L]
 
# If an existing asset or directory is requested, serve it
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
 
# If the requested resource doesn't exist, use the Angular app entry point
RewriteRule ^ /index.html

I've read Firebase's docs on Configuring Rewrites, but can't figure out how to target a specific User Agent.

Any ideas?

Questioner
Alex
Viewed
0
Frank van Puffelen 2020-11-29 22:45:09

Firebase Hosting doesn't support configuring rewrites based on the user-agent header. It can support rewrites based on the path, and rewrites based on the language of the user/browser.

The only option I know of to rewrite based on other headers, is to connect Firebase Hosting to Cloud Functions or Cloud Run and do the rewrite in code. But this is a significantly different exercise than configuring rewrites in the firebase.json file, so I recommend reading up on it before choosing this path.