简体   繁体   中英

apache mod_rewrite RewriteCond not ignoring files as expected

Rewrite engine is turned on (Apache2.2) and I'm trying to perform a simple url rewrite. The rewrite should not affect js and other static files. URL of interest: http://example.com/lib/js/my-js-file.js

This works: (request for .js file is not affected by re-write rule)

#exclude files from rewriting
RewriteCond %{REQUEST_FILENAME} !-f

#rewrite rule
RewriteRule ^(.*)$ /index.cfm/$1 [NS,L]

This also works: (request for .js file is not affected by re-write rule)

# exclude files from rewriting
RewriteCond %{REQUEST_FILENAME} !-f

# special rewrite
RewriteRule ^my-special-keyword/(.*)$ /index.cfm/something/cool/$1 [NS,L]

This fails: (attempted to use multiple rules and for some reason RewriteCond doesn't work and .js file is not loaded and instead "intercepted" by re-write rule)

# exclude files from rewriting
RewriteCond %{REQUEST_FILENAME} !-f

# special rewrite
RewriteRule ^my-special-keyword/(.*)$ /index.cfm/something/cool/$1 [NS,L]

# basic rule
RewriteRule ^(.*)$ /index.cfm/$1 [NS,L]

Why does the 3rd scenario fail?

This is very easy to solve. The problem is RewriteCond is per rewriterule so the condition is only being looked at for rewriterule right after it (your special rewrite). The last rewriterule now has no conditions so it's just processing the request.

So you either need to move rewritecond line under the special rewrite rule or add another one there above the basic rule. What I would do is just create a rule to ignore real files altogether on it's own. Then you don't have to have a condition for each rewrite rule. Try these rules.

# if the request is a real file  or real directory do nothing
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# else if special rewrite
RewriteRule ^my-special-keyword/(.*)$ /index.cfm/something/cool/$1 [NS,L]

# else basic rule
RewriteRule ^(.*)$ /index.cfm/$1 [NS,L]

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