问题
I have the following .htaccess file in a subdirectory of a site:
RewriteEngine On
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]
I have the following index.php file:
<html>
<head>
<link href="css/main.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<p>if css loads, this should be green</p>
<p id="message">javascript is NOT loaded</p>
<div>If images are displaying correctly, then there should be a green square below:</div>
<img src="images/test.jpg"/>
<div style="margin: 10px 0 0 0;font-weight: bold;background-color:#eee"><?php echo '$_SERVER["REQUEST_URI"] = '. $_SERVER["REQUEST_URI"]; ?></div>
</body>
</html>
All URLs are properly redirected to index.php. However, if the URL is more than one level deep below the sub-directory path, then my css/js/images paths are broken:

What do I have to change to the .htaccess file so that routing works at any level and doesn't break my css/js/image paths?
回答1:
From the absolute URL suggestions, if the files are always at the root of the domain, and if you're in control of the html, you could do the leading-slash absolute, which might avoid having to edit them among servers.
/css/main.css
/js/main.js
/images/test.jpg
htaccess rules can help if the files move, or you're not in control of the html. e.g., I work on project where some are using dreamweaver, which loves to do ../images/test.jpg.
RewriteRule (css|js|images)/(.+)$ /$1/$2 [NC,QSA,L]
This assumes the files are actually at the root of the domain. If that varies among servers, then you'll need to edit the paths in htaccess - but that's still easier than editing the html.
This assumes all the style, script and images are in the three folders css, js, images; and these are the only folders with these names. e.g., there can't be another images folder in some other subfolder.
This will break any folder ending in these strings, e.g., myimages or somecss. That can be avoided by tweaking the rule to require these to stand alone. Then those folders won't be changed, only the specific css, js, and images folders.
RewriteRule (?:^|/)(css|js|images)/(.+)$ /$1/$2 [NC,QSA,L]
The (?:^|/)
means non-capturing ?:
, at the beginning ^
or after a slash /
.
来源:https://stackoverflow.com/questions/17063235/why-does-htaccess-redirect-url-routing-fine-but-break-css-js-image-links-after