Nginx

Nginx 拒絕對文件夾文件不起作用

  • October 19, 2013

我試圖限制對我的網站的訪問,只允許特定的 IP,我遇到了以下問題:當我訪問 www.example.com 時,拒絕工作完美,但是當我嘗試訪問 www.example.com/index 時。 php 它返回“拒絕訪問”頁面,並且 php 文件直接在瀏覽器中下載,無需處理。我確實想拒絕訪問網站上除我之外的所有 IP 的所有文件。我該怎麼做?

這是我的配置:

server {
listen 80;
server_name example.com; 
root /var/www/example;

location / {
   index index.html index.php; ## Allow a static html file to be shown first
   try_files $uri $uri/ @handler; ## If missing pass the URI to front handler
   expires 30d; ## Assume all files are cachable
allow my.public.ip;
deny all;
}

location @handler { ## Common front handler
   rewrite / /index.php;
}
location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler
   rewrite ^(.*.php)/ $1 last;
}

location ~ .php$ { ## Execute PHP scripts
   if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss

   expires        off; ## Do not cache dynamic content
   fastcgi_pass   127.0.0.1:9001;
   fastcgi_param  HTTPS $fastcgi_https;
   fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
   include        fastcgi_params; ## See /etc/nginx/fastcgi_params
   }
}

好的,所以我找到了解決方案。Nginx 處理最精確的正則表達式,在這種情況下是 php 文件的正則表達式。要使配置正常工作,必須在 / location 規則中定義除 @handler 之外的所有其他位置(您不能置於任何規則之下 - 只能作為 root 使用者)

server {
listen 80;
server_name example.com; 
root /var/www/example;

   location / {
   index index.html index.php; ## Allow a static html file to be shown first
   try_files $uri $uri/ @handler; ## If missing pass the URI to front handler
   expires 30d; ## Assume all files are cachable
   allow my.public.ip;
   deny all;

   location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler
       rewrite ^(.*.php)/ $1 last;
   }

   location ~ .php$ { ## Execute PHP scripts
       if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss

       expires        off; ## Do not cache dynamic content
       fastcgi_pass   127.0.0.1:9001;
       fastcgi_param  HTTPS $fastcgi_https;
       fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
       include        fastcgi_params; ## See /etc/nginx/fastcgi_params
       }
}

   location @handler { ## Common front handler
       rewrite / /index.php;
   }

}

location @handler是完全不必要和多餘的,並且可能是問題的原因。您現有的indextry_files指令已經涵蓋了這一點。完全刪除location並修復try_files.

try_files $uri $uri/ /index.php;

引用自:https://serverfault.com/questions/546456