Modern favicons & htaccess rewrite rule

2020-02-15 03:43发布

Instead of having all the new favicon formats placed into the root directory of my website, I am placing them inside a subfolder.

To conform to the standards, as some browsers / device versions do not use the path as directed inside the html meta tags, but instead try to get the file from the website root anyway, I am creating a rewrite rule to redirect all these files to the actual location - but ONLY these files.

What I have come up with so far is the following :

RewriteEngine On
RewriteRule ^/((apple\-touch\-icon|android\-chrome|favicon|mstile)-([0-9]+)x([0-9]+).png|manifest\.json|browserconfig\.xml|favicon\.ico|(apple\-touch\-icon\-precomposed|apple\-touch\-icon).png|safari-pinned-tab.svg)$ /favicon/$1 [L]

This should match all of the following files :

favicons

When testing the rule at this site, the rule is not matched (see pic):

rule not matched

I would like to keep this rule on the same line, and due to the size standards changing, I wish to keep this dynamic (aka, instead of specifying each individual file, use a mask as I attempted to do). I suspect something with my regex is off.

Please assist or provide a solution with the corrected regex pattern for what I am intending to achieve.

1条回答
太酷不给撩
2楼-- · 2020-02-15 04:23

Modern favicons + Rewrite

Following is a fairly robust pattern for mapping the modern favicon's using rewrite.

Regex pattern, for reference

^(browserconfig.xml|manifest.json|safari-pinned-tab.svg|(android-chrome|favicon|mstile)-[0-9]+x[0-9]+.png|apple-touch-icon(-precompressed.png|-[0-9]+x[0-9]+.png|.png)|manifest.json)$

Usage: apply it to a rewrite rule (htaccess)

This example assumes the rewrite destination where the favicon's are placed is a folder named favicon (or whatever folder you wish).

RewriteRule ^(browserconfig.xml|manifest.json|safari-pinned-tab.svg|(android-chrome|favicon|mstile)-[0-9]+x[0-9]+.png|apple-touch-icon(-precompressed.png|-[0-9]+x[0-9]+.png|.png)|manifest.json)$ /favicon/$1 [L]
查看更多
登录 后发表回答