前言廢話
在開發 PHP 的過程中,我們常會使用 include
來引入其他文件。但你可曾想過,會不會有訪客直接去訪問這個被我們引入的文件?他進而變成一種漏洞?
因此,這篇文章就是來介紹,如何在 Nginx 中限制訪客訪問特定目錄。
目錄規劃
基本上,我會在當前目錄中,新增一個名為 include
的資料夾。之後,所有會被 include
的檔案都放在這裡面,例如:head.php
、db.php
這類型的。
之後當網站需要引入文件時,則改寫成這樣:
include("include/db.php");
編輯 Nginx 檔案
接著,我們要編輯 Nginx 中的 http server 配置。我們要加入下面這段話:
location ^~ /include/ {
deny all;
return 404;
}
完整版可能看起來像是這樣:
server {
listen 80;
root /var/www/example;
index index.php index.html index.htm;
server_name test.example.com;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ^~ /include/ {
deny all;
return 404;
}
}
之後驗證 Nginx 配置,看看有沒有什麼問題:
sudo nginx -t
如果沒有問題,就可以重啟 Nginx 啦!
sudo systemctl restart nginx