使用.htaccess重写所有子页面至指定目录并排除特定页面时,CSS、JS及图片文件加载异常的解决求助
Hey John, let's get your static assets loading properly while keeping your URL rewrite rules working as expected. The core issue here is that when you visit a URL like http://localhost/example.com/pencil, any relative paths to CSS/JS in your HTML (like css/style.css) get interpreted by the browser as http://localhost/example.com/pencil/css/style.css—which doesn't exist, since your assets are actually in the root example.com directory. Plus, we can clean up your existing .htaccess rules to be more efficient.
Here's a revised .htaccess configuration that fixes both problems:
RewriteBase /example.com/ RewriteEngine On ErrorDocument 404 /example.com/404.php <IfModule mod_rewrite.c> Options +FollowSymLinks # Handle specific pages (home, about-us, contact-us) with or without trailing slash RewriteRule ^(home|about-us|contact-us)/?$ $1.php [L,END] # Skip rewriting for existing files/directories (CSS, JS, images, etc.) RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] # Rewrite product URLs to item/index.php (handles with/without trailing slash) RewriteRule ^(.*)/?$ item/index.php?url=$1 [QSA,L] </IfModule>
Let me break down what this does:
- Consolidated specific page rules: Instead of separate rules for with/without trailing slashes, we use
^(home|about-us|contact-us)/?$to match both cases in one line. The[L,END]flags ensure that once a specific page is matched, no further rewrite rules run. - Skipped static assets: The two
RewriteCondlines check if the requested path is an existing file (-f) OR directory (-d). If so, theRewriteRule ^ - [L]tells Apache to leave it alone—so your CSS, JS, and images load normally without being redirected toitem/index.php. - Simplified product URL rule: We merged the trailing slash and non-trailing slash product rules into one using
^(.*)/?$, which keeps the code cleaner.
One extra tip: Make sure all your static asset references in HTML use absolute paths (like /example.com/css/style.css) instead of relative paths (like css/style.css). This ensures the browser always looks in the correct root directory for your assets, regardless of the current URL structure.
内容的提问来源于stack exchange,提问作者John




