Nginx deny index php

How to deny php files and allow some with Nginx?

I use on my site Drupal 8, the library «shariff-backend-php». https://github.com/heiseonline/shariff-backend-php When my server was on Apache, I had to add to my htaccess file the following line, otherwise the library would return a 403 error :

RewriteCond % !/shariff-backend-php/ 
 # For security reasons, deny access to other PHP files on public sites. # Note: The following URI conditions are not anchored at the start (^), # because Drupal may be located in a subdirectory. To further improve # security, you can replace '!/' with '!^/'. # Allow access to PHP files in /core (like authorize.php or install.php): RewriteCond % !/core/[^/]*\.php$ # Allow access shariff-backend-php. RewriteCond % !/shariff-backend-php/ # Allow access to test-specific PHP files: RewriteCond % !/core/modules/system/tests/https?.php # Allow access to Statistics module's custom front controller. # Copy and adapt this rule to directly execute PHP files in contributed or # custom modules or to run another PHP application in the same directory. RewriteCond % !/core/modules/statistics/statistics.php$ # Deny access to any other PHP files that do not match the rules above. # Specifically, disallow autoload.php from being served directly. RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F] 

Now my server has migrated to Nginx and htaccess files are useless. The library returns an error 403. How to apply the code of the htaccess file in the Nginx configuration file ? Here is the configuration file I use on my Drupal 8 installation :

server < server_name example.com; root /var/www/drupal8; ## location = /robots.txt < allow all; log_not_found off; access_log off; ># Very rarely should these ever be accessed outside of your lan location ~* \.(txt|log)$ < allow 192.168.0.0/16; deny all; >location ~ \..*/.*\.php$ < return 403; >location ~ ^/sites/.*/private/ < return 403; ># Block access to scripts in site files directory location ~ ^/sites/[^/]+/files/.*\.php$ < deny all; ># Allow "Well-Known URIs" as per RFC 5785 location ~* ^/.well-known/ < allow all; ># Block access to "hidden" files and directories whose names begin with a # period. This includes directories used by version control systems such # as Subversion or Git to store control files. location ~ (^|/)\. < return 403; >location / < # try_files $uri @rewrite; # For Drupal = 7 > location @rewrite < rewrite ^/(.*)$ /index.php?q=$1; ># Don't allow direct access to PHP files in the vendor directory. location ~ /vendor/.*\.php$ < deny all; return 404; ># In Drupal 8, we must also match new paths where the '.php' appears in # the middle, such as update.php/selection. The rule we use is strict, # and only allows this pattern with the update.php front controller. # This allows legacy path aliases in the form of # blog/index.php/legacy-path to continue to route to Drupal nodes. If # you do not have any paths like that, then you might prefer to use a # laxer rule, such as: # location ~ \.php(/|$) < # The laxer rule will continue to work if Drupal uses this new URL # pattern with front controllers other than update.php in a future # release. location ~ '\.php$|^/update.php' < fastcgi_split_path_info ^(.+?\.php)(|/.*)$; # Security note: If you're running a version of PHP older than the # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini. # See http://serverfault.com/q/627903/94922 for details. include fastcgi_params; # Block httpoxy attacks. See https://httpoxy.org/. fastcgi_param HTTP_PROXY ""; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param QUERY_STRING $query_string; fastcgi_intercept_errors on; # PHP 5 socket location. #fastcgi_pass unix:/var/run/php5-fpm.sock; # PHP 7 socket location. fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; ># Fighting with Styles? This little gem is amazing. # location ~ ^/sites/.*/files/imagecache/ < # For Drupal = 7 try_files $uri @rewrite; > # Handle private files through Drupal. Private file's path can come # with a language prefix. location ~ ^(/[a-z\-]+)?/system/files/ < # For Drupal >= 7 try_files $uri /index.php?$query_string; > location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ < try_files $uri @rewrite; expires max; log_not_found off; >> 

Источник

Читайте также:  Svg img height css

Set nginx.conf to deny all connections except to certain files or directories

I am trying to set up Nginx so that all connections to my numeric ip are denied, with the exception of a few arbitrary directories and files. So if someone goes to my IP, they are allowed to access the index.php file, and the phpmyadmin directory for example, but should they try to access any other directories, they will be denied. This is my server block from nginx.conf :

4 Answers 4

The easiest path would be to start out by denying all access, then only granting access to those directories you want. As ring0 pointed out, you can use the default (default_server in 0.8) flag on the listen directive. However, if you already have a server you want to use as a default for unknown named access to your host, you can also just catch requests without a host header or with your server’s ip address with something like this (replacing 1.2.3.4 with your server’s ip:

upstream _php < server unix:/var/run/php-fpm/php-fpm.sock; >server < server_name "" 1.2.3.4; root /path/to/root; index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # deny everything that doesn't match another location location / < deny all; ># allow loading /index.php location = / < ># need to allow GET / to internally redirect to /index.php location = /index.php < fastcgi_pass _php; ># allow access to phpmyadmin location /phpmyadmin/ < ># Allow access to static files in /phpmyadmin/ location ~ ^/phpmyadmin/.*\.php$ < fastcgi_pass _php; ># phpmyadmin php files > 

the fastcgi_params will be inherited by both locations that fastcgi_pass, and only /index.php and /phpmyadmin/ are allowed. I’ve also added an upstream block for php, which makes it easier should you ever need to add to or change it in the future.

Читайте также:  Оператор условия if else php

Источник

Кроме index.php, другие php файлы были недоступны для запуска. nginx настройка

Пожалуйста, подскажите как настроить так, что бы php файлы были не доступны для запуска, кроме index.php.
Пытаюсь делать вот так вот:

location ~\.php$ < deny all; >location ~ ^index.php

В этом случае все файлы в том числе index.php не доступны.
Вообще только стоит прописать один `location` с `deny all;`, как сразу же файлы не доступны и ничего не помогает.

Может стоит сделать редирект со всех файлов на index.php ?

ну и прочти как nginx обрабатывает локейшны (особенно внимательно прочти про то что regex обрабатываются по очереди, сначала верхний, а потом следующие)

Ну и поменяй локейшны местами и будет тебе счастье)

location = /index.php < allow all; >location ~ \.php$

Думал, на счет редиректа. Но, мне потом надо еще и другие файлы поставить в исключения. Т.е. не только index.php. Но, пока даже с index.php не получается.

Менял местами. Что только не пробовал. Ошибка на мой взгляд где-то в строке:

Выдает 404 ошибку. И не важно записать или нет локейшен deny all.

Посмотрел мануал. А так же getup посоветовал использовать вот эту конструкцию:

Что бы сайт работал, создал файл phpinfo.php.
Файлы php я НЕ выключал. Т.е. следующей конструкции в конфиге НЕТ:

Просто играюсь с одним файлом.
И вот какая фишка:

А в логах что?
DEBUG включи

ой, я тормоз, думал, что про апач тема. В nginx не помню.

Ты весь конфиг покажи, чтобы было от чего плясать.

В логах: 2014/02/20 08:41:17 [error] 77283#0: *1 access forbidden by rule, client: 95.28.143.56, server: http://www.mysite.ru, request: «GET /phpinfo.php HTTP/1.1», host: «http://www.mysite.ru»

 user www; worker_processes 8; error_log /var/log/nginx/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events < worker_connections 1024; >http < include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server < listen 80 default; client_max_body_size 100m; location / < root /usr/local/www/nginx-dist; index index.html index.htm index.php; >location ~ \00 < deny all; >location /phpMyAdmin < root /usr/local/www; index index.php; auth_basic "access restricted"; auth_basic_user_file htpasswd; >location ~ ^/phpMyAdmin.+\.php$ < root /usr/local/www; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/local/www$fastcgi_script_name; include fastcgi_params; >location ~ ^/phpMyAdmin.+\.(js|css|png|jpg|jpeg|gif|ico)$ < root /usr/local/www; expires max; log_not_found off; >location /phpmyadmin < rewrite ^/* /phpMyAdmin last; >location ~ \.php$ < fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/local/www/nginx-dist$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; >location ~ /\.ht < deny all; >> # #-------mysite.ru # server < listen 80; server_name www.mysite.ru mysite.ru; client_max_body_size 100m; access_log /var/log/nginx/mysite/access.log; error_log /var/log/nginx/mysite/error.log; location / < root /usr/local/www/mysite.ru; index index.html index.htm index.php; try_files $uri $uri/ /index.php?q=$request_uri; >location ~ \00 < deny all; >location /phpmyadmin < rewrite ^/* /phpMyAdmin last; >location ~ \.php$ < fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/local/www/mysite.ru$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; # deny all; >location = /phpinfo.php < allow all; >#location = / < # allow all; #>#location = /index.php < # allow all; #>location ~ /\.ht < deny all; >#my rules zufar location /2012-03-20-11-17-17/atom < rewrite ^(.*)$ http://www.mysite.ru/ redirect; >> # #-------mysite2.biz # server < listen 80; server_name www.mysite2.biz mysite2.biz mysite2.ru www.mysite2.ru; client_max_body_size 100m; access_log /var/log/nginx/mysite2/access.log; location / < root /usr/local/www/mysite2.biz; index index.html index.htm index.php; try_files $uri $uri/ /index.php?q=$request_uri; >location ~ \00 < deny all; >location ~ \.php$ < fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/local/www/mysite2.biz$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; >location ~ /\.ht < deny all; >> # ---- dns control server < listen 37073; server_name dcontrol.mysite2.biz; access_log /var/log/nginx/dcontrol/access.log; location / < root /usr/local/www/dcontrol; index index.html index.htm index.php; auth_basic "access restricted"; auth_basic_user_file htpasswd; >location ~ \00 < deny all; >location ~ \.php$ < fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/local/www/dcontrol$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; >location ~ /\.ht < deny all; >> > 

Источник

Оцените статью