Only allow certain file extensions?

What is the best way to enforce that nginx only serves content to a list
of known good extensions (like .php, .css, .xml, .jpg etc) and does a
deny all on all other page types?

I was thinking of using a location block for this, like so:

location NOT ~* regex_with_valid_extensions {
access_log /deny.log main;
deny all;
}

But I wasn’t sure how to do a NOT (make the regex match if the regex was
false. Also I was thinking perhaps there is a better way?

In summary I have two rules. Rule #1 is that certain known bad
extensions I want blocked, for example .xyz. Rule #2 is that I want to
allow only good known extensions, like .htm, .css, .jpg, .gif etc.

So I want my rule to be that it cannot match the denied extension(s) and
it must also pass the allowed extensions.

I know it is a bit repetitive because since .xyz would not be in the
allowed extensions then it would by default be blocked. But just to be
certain I’d like it to work this way.

Any suggestions on the best approach to do this, without then messing up
the subsequently location blocks from matching?

Thank you!

On Tue, Feb 24, 2009 at 09:58:46PM -0800, Rt Ibmer wrote:

In summary I have two rules. Rule #1 is that certain known bad extensions I want blocked, for example .xyz. Rule #2 is that I want to allow only good known extensions, like .htm, .css, .jpg, .gif etc.

So I want my rule to be that it cannot match the denied extension(s) and it must also pass the allowed extensions.

I know it is a bit repetitive because since .xyz would not be in the allowed extensions then it would by default be blocked. But just to be certain I’d like it to work this way.

Any suggestions on the best approach to do this, without then messing up the subsequently location blocks from matching?

 location / {
     ...
 }

 location ~ \.(htm|css|jpg|gif)$ {
     ...
 }

 location ~ \.php$ {
     ...
 }

 location ~ \.[^\.]+$ {
     deny all;
 }

On Wed, Feb 25, 2009 at 7:34 AM, Igor S. [email protected] wrote:

location ~ \.(htm|css|jpg|gif)$ {
    ...
}

Igor, Is it case sensitive?
I have been bitten by it before :slight_smile:

On Wed, Feb 25, 2009 at 11:54:20PM +0100, Atif G. wrote:

On Wed, Feb 25, 2009 at 7:34 AM, Igor S. [email protected] wrote:

location ~ \.(htm|css|jpg|gif)$ {
    ...
}

Igor, Is it case sensitive?

Yes.
Use “~*” for case insensitive regex.

BTW, I did not see the origianl email. Just the answer: