.htaccess虚拟文件夹下CSS、图标文件加载失败问题求助
Hey there! Let's work through your problem step by step—first we'll unpack that confusing regex, then fix the CSS/icon loading issue.
1. What does ^([^.]+)$ mean?
Let's break this regular expression down piece by piece:
^: Matches the start of the URL path string.([^.]+): This is a capture group. The[^.]means "match any character that is NOT a dot", and the+means "match this one or more times". So together, this captures any sequence of characters that has no dots in it.$: Matches the end of the URL path string.
In short, this rule targets URLs like products/add (no dots) but ignores URLs with dots, like css/style.css or images/icon.ico.
2. Why aren't your CSS and icons loading?
The problem is relative paths. When you visit mysite.com/products/add, your browser treats /products/add as the current "directory". So if your HTML has a relative link like <link href="css/style.css">, the browser will request mysite.com/products/css/style.css instead of the actual location mysite.com/css/style.css—hence the missing resources.
3. Fixing the resource loading issue
You've got two straightforward fixes here, depending on what's easier for you:
Option 1: Use absolute paths for resources
The simplest fix is to update all your CSS, icon, and script links to use absolute paths (starting with a /). For example:
Instead of:
<link href="css/style.css"> <img src="icons/logo.ico">
Use:
<link href="/css/style.css"> <img src="/icons/logo.ico">
This tells the browser to always load resources from the root of your site, no matter what virtual path you're visiting.
Option 2: Update your .htaccess to skip real files/directories
Add these lines before your existing rewrite rule. They tell Apache to ignore the rewrite rules if the requested file or directory actually exists on your server:
# Skip rewrite if the request is for a real file (like CSS, icons) RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ - [L] # Skip rewrite if the request is for a real directory RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L]
Now when the browser requests /css/style.css, Apache sees it's a real file and serves it directly, instead of applying your virtual products folder rule.
4. Modifying ^([^.]+)$ if you need dots in virtual paths
If you ever need virtual paths with dots (like products/item.123), the original regex will break because it excludes all paths with dots. To fix this, update the rule to ignore only common resource file extensions:
# Match paths that don't end with CSS/JS/PNG/JPG/ICO/SVG RewriteRule ^((?!\.(css|js|png|jpg|ico|svg)$).+)$ your-target-file.php?path=$1 [L]
The (?!\.(css|js|png|jpg|ico|svg)$) part is a "negative lookahead"—it tells Apache to skip any path that ends with those extensions, while still allowing dots elsewhere in the virtual path.
内容的提问来源于stack exchange,提问作者Emraan Aly

