Abijeet Patro
Abijeet Patro

Reputation: 2884

.htaccess to route request to current folder

I'm writing a custom PHP framework for use on my projects and I'm having some issues loading the CSS, JS and image files.

The following code is in my .htaccess file -

RewriteEngine On
#rewrite to base folder
RewriteBase /SimplexFramework/

#add trailing slashes
RewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ $1/ [NC,R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

This basically states that redirect request to index.php if the path doesn't point to a file.

Following is my directory structure. CSS, JS folders are present under files. enter image description here

My view files are located in app/view, I'm loading the CSS and JS files through the path - files/css/style.css or files/js/script.js

When my URL in the browser is http://localhost:8081/SimplexFramework/ things work as expected.

When the URL changes to http://localhost:8081/SimplexFramework/Users/login for example, apache can no longer find the files as expected.

In the browser I see the following request made -

http://localhost:8081/SimplexFramework/User/register/files/js/scrits.js

Can I ask apache to look for files from the folder in which I have .htaccess. Something similar to RewriteBase ?

Upvotes: 0

Views: 1095

Answers (1)

Jon Lin
Jon Lin

Reputation: 143966

When you have relative URLs in your content, it's up to the browser to figure out how to load them. This has nothing to do with htaccess or rewrite rules.

Say a browser loads this url: http://localhost:8081/SimplexFramework/Users/login

And on that page's content, it see's a link: <script src="files/js/scripts.js">

Since the link is relative (doesn't start with a "http" or "/"), the browser now has to guess what the relative URL base is, and the only thing it has to work with is the URL. So the last path in the URL is "login", and it drops that and uses the basename as the URL base, so it gets:

http://localhost:8081/SimplexFramework/Users/files/js/scripts.js

This is 100% a relative/absolute URL issue and has nothing to do with your rules and nothing to do with RewriteBase. It's because your links are relative and the URL base has changed from http://localhost:8081/SimplexFramework/ to http://localhost:8081/SimplexFramework/some/stuff/that/eventually/gets/rewritten/.

To fix this, make your URL's absolute: <script src="/SimplexFramework/files/js/scripts.js">

or add the correct URL base to the header of your pages:

<base href="/SimplexFramework/" />

Upvotes: 2

Related Questions