Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect all requests to a file, except images using Apache?

I have an .htaccess file with the following contents:

Options +FollowSymLinks +ExecCGI

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^(.*)$ entryPoint.php [QSA]
</IfModule>

With this, I want all requests to be redirected to the file entryPoint.php so that it can examine them:

  • If there is no extension, is must be a module
  • If there's a .php, it's a hacking
  • If it's a .png, then it's a "safe" call.

    In case of images, I used to output headers, and file_get_contents() their content. I figured out it's a bit slower than leaving a direct read.

My question is:

How to prevent this .htaccess from calling entryPoint.php if there are references for images?

Extra feedback on the code I already have is greatly appreciated!

like image 290
user893856 Avatar asked Aug 15 '11 01:08

user893856


3 Answers

As I understand you want to process all non-images threw your php file. Right?

If so, then here is what you need:

Options +FollowSymLinks +ExecCGI

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteCond %{REQUEST_URI}  !(\.png|\.jpg|\.gif|\.jpeg|\.bmp)$
RewriteRule (.*)  entryPoint.php [QSA]

</IfModule>

Remember to add to delete any image extension you want! If I misunderstood,Please tell me to correct my answer!

like image 143
undone Avatar answered Nov 17 '22 18:11

undone


You can use something like this to stop rewriting images

RewriteRule \.(jpg|png)$ - [L]

This rule says 'if the requested file ends with a period followed by either "jpg" or "png" then don't rewrite it.'

The $ character just marks "the end of the string/filename", the - says "don't rewrite the URL if this rule matches", and the [L] means "don't process any more rules if this one matches.

I'll add that the usual way of dealing with this sort of thing is to just apply a blanket statement of "if this file exists just serve the file up directly, but anything that doesn't exist gets processed by PHP." That type of rule looks like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?request=$1 [L,QSA]

This says "if the request isn't for a file or directory that exists, pass the request to index.php with the original path passed as a query string parameter called 'request', appending any other query string parameters to the new request."

like image 27
AgentConundrum Avatar answered Nov 17 '22 20:11

AgentConundrum


RewriteCond %{REQUEST_FILENAME} !\.(png|jpg|gif)$

Put this line right before your RewriteRule

like image 7
zerkms Avatar answered Nov 17 '22 20:11

zerkms