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

江枫思渺然 提交于 2019-11-27 15:45:07

问题


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!


回答1:


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!




回答2:


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."




回答3:


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

Put this line right before your RewriteRule



来源:https://stackoverflow.com/questions/7060932/how-to-redirect-all-requests-to-a-file-except-images-using-apache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!