Effectiveness of multiple locations and less if directives

António P. P. Almeida appa at perusio.net
Fri Jan 14 22:34:32 MSK 2011


On 14 Jan 2011 19h03 WET, aryanto at chello.at wrote:

> I am sorry for being a bit pushy, but it would be great if I could
> get an answer for my question.
>
> On 10/01/11 01:09, Anto wrote:
>> Hello everybody,
>>
>> I would like to restrict the direct access for instance, to *.txt
>> files except sitemap.txt and robots.txt. And no direct access also
>> to any *.php files except index.php and upgrade.php. I also would
>> like to prevent the "try_files" to discover and serve any *.php
>> files as they should be passed on to fastcgi backend. According to
>> the recommendation, I should use as less "if" directive inside
>> "location" as possible. So I ended up with the settings similar
>> like below. My actual settings are longer than that.
>>
>> If I would combine some "location" directives into one, but use
>> more "if" directives and regular expressions, would that make nginx
>> performs the processing ineffectively which in the end makes it
>> slower?
>>
>> Kind regards,
>>
>> Anto
>>
>> =================================================================
>> server {
>>
>> server_name mysite.eu;
>> root /home/www/mycms;
>> access_log /home/www/mycms/myvhost1/logs/nginx_access.log;
>> valid_referers mysite.eu *.mysite.eu;
>>
>> if ( $request_method !~ ^(GET|HEAD|POST)$ ) {
>> return 410;
>> }
>>
>> location = /favicon.ico {
>> rewrite /favicon.ico /myvhost1/favicon.ico break;
>> expires max;
>> log_not_found off;
>> access_log off;
>> }
>>
>> location = /sitemap.txt {
>> rewrite /sitemap.txt /myvhost1/sitemap.txt break;
>> log_not_found off;
>> access_log off;
>> }
>>
>> location = /robots.txt {
>> log_not_found off;
>> access_log off;
>> }
>>
>> location = / {
>> rewrite ^ /index.php?arg=page/0 last;
>> }
>>
>> location ~* \.(txt|log|php|inc|sh|pl|py)$ {
>> return 410;
>> log_not_found off;
>> }
>>
>> location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
>> if ($invalid_referer) {
>> return 410;
>> }
>> expires max;
>> log_not_found off;
>> access_log off;
>> }
>>
>> location / {
>> try_files $uri @mod_uri;
>> }
>>
>> location @mod_uri {
>> rewrite ^/(.*)$ /index.php?arg=$1 last;
>> }
>>
>> location = /upgrade.php {
>> if ($invalid_referer) {
>> return 410;
>> }
>> include fastcgi_params;
>> fastcgi_pass unix:/tmp/fastcgi.sock;
>> }
>>
>> location = /index.php {
>> include fastcgi_params;
>> fastcgi_pass unix:/tmp/fastcgi.sock;
>> }
>> }

This is how I do it in my drupal config:

The last location stanza is:

## Any other attempt to access PHP files returns a 404.
location ~* ^.+\.php$ {
   return 404; 
}

Other PHP/FastCGI locations appear before that enumerate *all*
accessible PHP files.

Cf. https://github.com/perusio/drupal-with-nginx for details.

--- appa







More information about the nginx mailing list