简体   繁体   中英

htaccess trailing slashes break css and js files

Ok so although this sort of htaccess questions are asked a lot, i could not find a (partial) solution that worked for my case.

So I have this system that can be placed in any system such as localhost/system or localhost/folder/here

anyhow, the system uses a file index.php and .htaccess file and an url like localhost/system/param1/param2/param3 should just refer to the index.php file however, the stylesheet placed in localhost/system/css/ should still be available when called upon.

Htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php [L,QSA]

index.php:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>MyPage</title>
    <link rel='stylesheet' type='text/css' href='css/style.css' />
    <script src='js/index.js'></script>
</head>

<body>
content...
</body>
</html>

As you can see, I like to keep the paths relative. When the url http://localhost/system/param1 is being used it works... however when an url such as http://localhost/system/param1/ or http://localhost/system/param1/param2/etc .. is used it no longer works because the links will not refer to the correct path

How can i solve this issue? As I said, stack has multiple topics about this but i couldn't find one solving relative paths.

The answer partly provided by the answers:

<?php
$basePath = str_replace('index.php', '', $_SERVER['PHP_SELF']);
echo "<base href='{$basePath}' />";
?>

By placing this on the top of my html header it worked and it allowed me to simply move the system without editing code each time I do so.

Depending on how you've built your site, it's often easiest in these cases to just set a base URL. Put this as the second element in your <head> tag, right after your character set declaration:

<base href="https://example.com/" />

Now, everything on the page is relative to https://example.com/ .

(Of course, substitute in whatever base you want. If you really are just using the root of the site as the base everywhere, you can simply drop this and use full path when referencing your CSS files, starting with / .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM