如何限制對伺服器上的“/”和“/index.php”的訪問,但不允許其他任何內容?

如何限制對伺服器上的“/”和“/index.php”的訪問,但不允許其他任何內容?

我希望允許使用者只能存取index.php(也只能/)我的伺服器,而不能存取其他任何內容(如果有效則傳回 403,如果檔案無效則傳回 404)。

我怎樣才能做到這一點?我嘗試過以下解決方案 拒絕存取除index.html之外的所有檔案apache

拒絕存取除index.php之外的所有文件,但允許透過htaccess文件中的“/”訪問

但它們似乎沒有任何效果。

我的 .htaccess 檔案是這樣的,但它沒有任何效果,我仍然可以存取伺服器上的其他檔案:

Order allow,deny
Deny from all
<FilesMatch index\.php>
        Allow from all
</FilesMatch>

我不確定是否還需要在虛擬主機配置中定義任何內容?

我的虛擬主機檔案是:

ServerAdmin webmaster@localhost
ServerName server.mydomain.com
ServerAlias server.mydomain.com
DocumentRoot /var/www/server.mydomain.com
DirectoryIndex index.php
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

SSLCertificateFile /etc/letsencrypt/live/server.mydomain.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/server.mydomain.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf

apache2ctl -S 輸出是:

VirtualHost configuration:
*:443                  server.mydomain.com (/etc/apache2/sites-enabled/server.mydomain.com-le-ssl.conf:2)
*:80                   server.mydomain.com (/etc/apache2/sites-enabled/server.mydomain.com.conf:1)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex ssl-stapling: using_defaults
Mutex ssl-cache: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
Mutex ssl-stapling-refresh: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33

答案1

恕我直言,您正在以錯誤的方式處理事情,並試圖解決一個可以完全避免的問題:

只是不要在 DocumentRoot 中儲存不屬於線上的檔案和目錄。

將目錄的內容限制/var/www/server.example.com為僅該index.php文件,這樣就不會出錯。


這個問題帶有歷史標籤此版本和語法不適合目前的 Apache httpd 2.4 版本。 - 看https://httpd.apache.org/docs/2.4/upgrading.html


當您確實想發布某些內容時,http://www.example.com/some-path/ 請使用Alias指令完全公開不同的目錄而不是建立子目錄/var/www/server.example.com/some-path/ (例如 create /var/www//some-path)並使用:

<VirtualHost *:80
    ServerAdmin webmaster@localhost
    ServerName server.mydomain.com
    ServerAlias server.mydomain.com
    DocumentRoot /var/www/server.example.com

    Alias /some-path "/var/www/some-path"

    <Directory "/var/www/some-path"> 
       # add settings here, for example
       Order deny,allow
       Deny from all
       Allow From 127.0.0.1
    </Directory>
</VirtualHost>

相關內容