RobC RobC - 11 months ago 55
Apache Configuration Question

htaccess RewriteRule problems

I have a web page which works fine on live server. However some links to files (jpg, pdf and others) which are created with cms editor contain relative paths.
When I run that page on my local test server which serves the pages out of a sub folder of localhost the relative paths to the files are wrong since they are missing the subfolder at the beginning. The html page loads fine. It's just some files in it that have wrong path and won't load.

page loads from http://localhost/level1/

files are trying to load from http://localhost/level2/ and I get 404s.

They should be loading from http://localhost/level1/level2/

So I setup a RewriteRule to correct the path but no matter what I have tried I can't get it to work. I have tried various flags including [R,L] but nothing changes the URI in the html.

currently I have:

RewriteRule ^/level2/(.*)$ /level1/level2/$1 [R]

Any suggestions?


Answer Source

Sounds like those links are not relative paths but absolute ones (starting with a leading slash (/). That is why the issue occurs at all. Relative paths make much more sense.

This would be the version to be used inside your http servers host configuration:

RewriteEngine on
RewriteRule ^/level2/(.*)$ /level1/level2/$1 [L,QSA]

Here the version for .htaccess style files (note the missing leading slash):

RewriteEngine on
RewriteRule ^level2/(.*)$ /level1/level2/$1 [L,QSA]

You could use a version that can be used in both situations:

RewriteEngine on
RewriteRule ^/?level2/(.*)$ /level1/level2/$1 [L,QSA]

Note however that in general one should always prefer to place such rules inside the http servers host configurations. .htaccess style files are notoriously error prone, hard to debug and they really slow down the server, often for nothing. .htaccess style files only offer a last option for those who are using a really cheap web hosting provider. Or for situations where a web application has to write its own rewrite rules, which obviously is a security nightmare on its own...