Forum Moderators: phranque

Message Too Old, No Replies

mod rewrite negative match not working

Trying to stop re-writing of actual files/directories

         

trillianjedi

10:17 am on Feb 14, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi gang!

Been a while since I had one of these issues, but I'm on holiday so building something for fun as my office won't allow me to write code anymore :)

I'm playing with a REST-ful API that has a website on the same server and I want to match the first directory and map that to a .php file. I want to ignore everything else, so my static html, php, cs, js etc files remain as is. EG:-

https://example.com/123-abc/ . <-- gets mod_rewritten to https://example.com/myfile.php?q=123-abc

BUT

https://example.com/js/jquery.js <-- does not get mod_rewritten because it's an actual file that really exists

After some googling, thinking and trial and error I came up with this:-


Options +FollowSymLinks
RewriteEngine On
LogLevel alert rewrite:trace6
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /myfile.php?q=$1 [L,QSA]


I believe the RewriteRule is working correctly because the matches that I did want to catch are working.

However, all my javascript, css etc is getting matched and re-written too.

My intention/understanding was that these two lines:-


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d


... would prevent from re-writing the existing files and existing directories.

I slept on this to see if I could spot my mistake in the morning, but I can't. I'm hoping someone here can :)

Thanks!

PS - I don't know if it makes a difference, but I haven't put this in .htaccess - I have put it in my apache default-ssl config file.

phranque

1:54 pm on Feb 14, 2017 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



try this:

Options -MultiViews
https://httpd.apache.org/docs/2.2/mod/core.html#options

i don't think this is your problem but you might also need this:

AcceptPathInfo Off
https://httpd.apache.org/docs/2.4/mod/core.html#acceptpathinfo

you might also want a preceding RewriteCond to exclude requests for myfile.php from being further processed by the ruleset.

lucy24

7:32 pm on Feb 14, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Whenever possible, avoid the !f and !d tests, since the server has to perform these tests on every single request. Instead, have something like this before the CMS-or-whatever rewrite code:

RewriteRule \.(js|css|jpg|png|ico)$ - [L]
listing any extension (case sensitive) that actually exists on your site. This will not prevent the server from returning a 404 further down the line if it turns out you goofed and some particular non-page file really doesn't exist. It will just stop mod_rewrite from getting involved.