developer tip

index.php를 제외한 모든 .php 파일에 대한 직접 액세스 거부

optionbox 2020. 10. 18. 09:21
반응형

index.php를 제외한 모든 .php 파일에 대한 직접 액세스 거부


.php하나를 제외한 모든 파일에 대한 직접 액세스를 거부하고 싶습니다 .index.php

다른 .php파일에 대한 유일한 액세스 는 php를 통해서 여야합니다 include.

가능하다면 모든 파일을 같은 폴더에두고 싶습니다.

최신 정보:

일반적인 규칙은 좋을 것이므로 모든 파일을 살펴볼 필요는 없습니다. 위험은 내가 파일이나 줄을 잊어 버린 것입니다.

업데이트 2 :

index.php폴더에www.myadress.com/myfolder/index.php

해당 폴더의 모든 .php파일 myfolder및 하위 폴더 대한 액세스를 거부하고 싶습니다 .


index.php에서 다음과 같은 액세스 값을 추가합니다.

$access = 'my_value';

다른 모든 파일에서 단일 바이트라도 php에 의해 에코되기 전에이 검사를 포함하십시오.

if(empty($access)) {
    header("location:index.php"); 
    die();
}

이렇게하면 다른 php 파일은 URL이 아닌 require / include를 통해서만 액세스 할 수 있습니다.


정말 하시겠습니까? 심지어 CSS와 JS 파일과 이미지와 ...?

좋아, 먼저 mod_access가 apache에 설치되어 있는지 확인한 다음 .htaccess에 다음을 추가하십시오.

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

<Files /index.php>
    Order Allow,Deny
    Allow from all
</Files>

첫 번째 지시문은 로컬 호스트를 제외한 모든 파일에 대한 액세스를 금지합니다. Order Deny,Allow, 허용이 나중에 적용 되기 때문에 두 번째 지시문은 index.php에만 영향을줍니다.

주의 사항 : 주문 줄에서 쉼표 뒤에 공백이 없습니다.

* .css 또는 * .js와 일치하는 파일에 대한 액세스를 허용하려면 다음 지시문을 사용하십시오.

<FilesMatch ".*\.(css|js)$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

당신은에 대한 지침을 사용할 수 없습니다 <Location>또는 <Directory>하지만, .htaccess 파일 내부.

귀하의 옵션은 <FilesMatch ".*\.php$">첫 번째 허용, 거부 그룹 주위에서 사용한 다음 명시 적으로 index.php에 대한 액세스를 허용하는 것입니다.

Apache 2.4 업데이트 : 이 답변은 Apache 2.2에 적합합니다. Apache 2.4에서는 액세스 제어 패러다임 이 변경되었으며 올바른 구문은 Require all denied.


사실 나는 주제의 작성자와 같은 질문으로 여기에 왔지만 주어진 해결책 중 어느 것도 내 문제에 대한 완전한 대답이 아닙니다. 한 번만 구성 할 수 있는데 서버의 모든 파일에 코드를 추가하는 이유는 무엇입니까? 가장 가까운 것은 Residuum의 파일이지만 index.php라는 이름이없는 php 파일 만 제외하고 싶을 때 여전히 모든 파일을 제외하고있었습니다.

그래서 이것을 포함하는 .htaccess를 생각해 냈습니다.

<Files *.php>
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
</Files>

<Files index.php>
    Order Allow,Deny
    Allow from all
</Files>

(htaccess 파일은 재귀 적으로 작동하므로 질문의 전제 조건에 완벽하게 적합합니다.)

우리가 간다. 사용자가 접근 할 수있는 유일한 php 파일은 index.php 파일입니다. 그러나 여전히 모든 이미지, CSS 스타일 시트, js 스크립트 등에 액세스 할 수 있습니다.


질문에 대한 비스듬한 대답은 index.php 파일을 제외한 모든 코드를 클래스로 작성하는 것입니다. 클래스를 포함하는 PHP 파일은 Apache를 통해 직접 호출 되더라도 아무 일도 일어나지 않습니다.

직접적인 대답은 .htaccess에 다음을 포함하는 것입니다.

<FilesMatch "\.php$">
    Order Allow,Deny
    Deny from all
</FilesMatch>
<FilesMatch "index[0-9]?\.php$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

이렇게하면 index.php, index2.php 등과 같은 파일에 액세스 할 수 있지만 다른 .php 파일에 대한 액세스는 거부됩니다. 다른 파일 형식에는 영향을주지 않습니다.


상수를 정의하고 index.php다음과 같이 추가 할 수 있습니다.

if (!defined("YOUR_CONSTANT")) die('No direct access');

다른 파일의 시작 부분에.

또는 다음 mod_rewrite.htaccess같이 편집하여 요청을 사용 하고 index.php로 리디렉션 할 수 있습니다 .

RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ /index.php/$1 [L,R=301]

그런 다음 index.php에서 들어오는 모든 요청을 분석하고 적절한 조치를 취할 수 있어야합니다.

If you want to leave out all *.jpg, *.gif, *.css and *.png files, for example, then you should edit second line like this:

RewriteCond $1 !^(index\.php|*\.jpg|*\.gif|*\.css|*\.png)

How about keeping all .php-files except for index.php above the web root? No need for any rewrite rules or programmatic kludges.

Adding the includes-folder to your include path will then help to keep things simple, no need to use absolute paths etc.


URL rewriting could be used to map a URL to .php files. The following rules can identify whether a .php request was made directly or it was re-written. It forbids the request in the first case:

RewriteEngine On
RewriteCond %{THE_REQUEST} ^.+?\ [^?]+\.php[?\ ]
RewriteRule \.php$ - [F]
RewriteRule test index.php

These rules will forbid all requests that end with .php. However, URLs such as / (which fires index.php), /test (which rewrites to index.php) and /test?f=index.php (which contains index.php in querystring) are still allowed.

THE_REQUEST contains the full HTTP request line sent by the browser to the server (e.g., GET /index.php?foo=bar HTTP/1.1)


Instead of passing a variable around I do this which is self-contained at the top of any page you don't want direct access to, this should still be paired with .htaccess rules but I feel safer knowing there is a fail-safe if htaccess ever gets messes up.

<?php
// Security check: Deny direct file access; must be loaded through index
if (count(get_included_files()) == 1) {
    header("Location: index.php"); // Send to index
    die("403"); // Must include to stop PHP from continuing
}
?>

An easy solution is to rename all non-index.php files to .inc, then deny access to *.inc files. I use this in a lot of my projects and it works perfectly fine.


With Apache 2.4, the syntax for access control has changed. If using directives like:

Order deny,allow
Deny from all

does not work, you're likely using Apache 2.4.

The Apache 2.4 docs are here.

You need to use Require all denied in one of these ways:

# you can do it this way (with "not match")

<FilesMatch ^((?!index\.php).)*$>
  Require all denied
</FilesMatch>

# or 

Require all denied

<Files index.php>
  Require all granted
</Files>

place all files in one folder. place a .htaccess file in that folder and give it the value deny all. then in index.php thats placed outside of the folder have it echo out the right pages based on user input or event


<Files ~ "^.*\.([Pp][Hh][Pp])">
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

Allow only 2 ip , all other will block

Order Deny,Allow
Deny from all
Allow from 173.11.227.73 108.222.245.179

참고URL : https://stackoverflow.com/questions/1340001/deny-direct-access-to-all-php-files-except-index-php

반응형