Nginx deny не работает для файлов папок
Я пытаюсь ограничить доступ к своему сайту, чтобы разрешить только определенные IP-адреса, и у меня возникает следующая проблема: когда я захожу на www.example.com, deny работает отлично, но когда я пытаюсь зайти на 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
}
}
2 ответа
Итак, я нашел решение. 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
является совершенно ненужным и избыточным, и, вероятно, является причиной проблемы. Это уже покрыто вашим существующим index
а также try_files
директивы. Удалить location
целиком и исправить try_files
,
try_files $uri $uri/ /index.php;