WordPress跨域迁移后字体图标失效,CORS策略拦截问题求助
Hey, let's sort out this font icon CORS issue you're facing post-domain migration. I've run into similar problems when moving WordPress sites between domains, so here are practical fixes that should resolve it:
1. Configure CORS via .htaccess (Apache Servers)
Since WordPress often runs on Apache, adding CORS rules directly to your root .htaccess file is usually the fastest fix. The PHP header you tried earlier only affects PHP-generated content, but font files are static assets handled directly by the server—so server-level config is needed.
Add this code after the RewriteEngine On line in your .htaccess:
# Allow CORS for font files <FilesMatch "\.(ttf|otf|eot|woff|woff2)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch>
If you want to restrict it to only your two domains (more secure), replace "*" with "https://your-old-domain.com https://your-new-domain.com" (adjust to your actual domain URLs).
2. Nginx Server Configuration
If your site uses Nginx, add these rules inside your site's server block in nginx.conf or your site-specific config file:
# Allow CORS for font files location ~* \.(ttf|otf|eot|woff|woff2)$ { add_header Access-Control-Allow-Origin "*"; # Or restrict to specific domains: # add_header Access-Control-Allow-Origin "https://your-old-domain.com https://your-new-domain.com"; }
After making changes, restart Nginx with sudo systemctl restart nginx.
3. Check for Hardcoded Domain References in Font Paths
Sometimes themes or plugins hardcode the old domain in font URLs. Do a quick check:
- Go to Appearance > Theme File Editor and look through your theme's
functions.phpor custom CSS files for references to your old domain (e.g.,https://abcd.com/wp-content/themes/your-theme/fonts/). - Replace any hardcoded old domain with relative paths (like
/wp-content/themes/your-theme/fonts/) or use WordPress's built-inget_template_directory_uri()function to dynamically get the correct URL.
4. Clear All Caches
CORS issues often stick around due to cached content. Make sure to clear:
- Your browser's cache (Ctrl+Shift+Delete on most browsers)
- WordPress caching plugin (if you use one like WP Rocket, W3 Total Cache)
- CDN cache (if you're using Cloudflare, StackPath, etc.)
Why Your Previous Fixes Didn't Work
The PHP header you added only applies to pages generated by PHP, not static font files. Similarly, changing how you load fonts in the head won't bypass server-level CORS restrictions—those are enforced before the browser even processes your page's HTML.
内容的提问来源于stack exchange,提问作者Azad Chouhan

