Excluding files from htaccess rewrite rules

2020-03-05 03:01发布

I have an htaccess rewrite setup in my PHP application to route files via the bootstrapper file. In essence, the goal is to take a URL such as www.domain.com/view/key/value/key/value where the view would route accordingly and the key/value pairs would be available via a function I wrote in the bootstrapper to the views. All was working well...

That is, until I started doing ajax-y stuff. I'm routing all my ajax queries through a single file, ajaxDispatcher.php. When I did that, the htaccess (correctly) caught the request and used my bootstrapper to route it inappropriately. Similarly, it was attempting to route unwanted files such as .ico, .css, etc.

I figured out the file extension routing exception, however, I've not been able to have .htaccess ignore rewrite rules for the single file ajaxDispatcher.php. Here's where my code stands:

 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^/ajaxDispatcher.php$ $0 [L]
 RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php?route=$1 [L]

How do I get .htaccess to ignore the routing rules only for ajaxDispatcher?

2条回答
来,给爷笑一个
2楼-- · 2020-03-05 03:44

If you remove the ajaxDispatcher.php line from the code you show, it should work - because of the !-f and !-d rules, requests to files that actually exist will be excluded from the rewrite ruke.

查看更多
混吃等死
3楼-- · 2020-03-05 03:53

You should move your new rule atop the RewriteCond block:

RewriteRule ^/?ajaxDispatcher.php$ - [L]

Otherwise the RewriteConditions don't cover the extensions RewriteRule anymore, for which I assume they are intended.

Another alternative is turning it into another RewriteCond of course:

RewriteCond %{SCRIPT_NAME}  !ajaxDispatcher

Or injecting it as assertion into the final RewriteRule (?!ajaxDispatcher.php).

The ordering thing is best explained on Serverfault: https://serverfault.com/questions/214512/everything-you-ever-wanted-to-know-about-mod-rewrite-rules-but-were-afraid-to-as

查看更多
登录 后发表回答