这些是配置基于 MVC 的 Web 应用程序的一般适用步骤。以下设置的假定 Web 服务器版本:Apache HTTP Server v2.4。
1) 阻止对所有目录和文件的访问:
首先,在Apache的配置文件中,默认情况下应该阻止对所有目录和文件的访问:
# Do not allow access to the root filesystem.
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
# Prevent .htaccess and .htpasswd files from being viewed by Web clients.
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
2) 允许访问默认目录:
然后应该允许访问默认目录(此处为/var/www/),假定用于项目:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
我的建议:出于安全原因,这个位置应该只包含一个index.php 和一个index.html 文件,每个文件都显示一个简单的"你好” 消息。所有 Web 项目都应在其他目录中创建,并且应单独设置对它们的访问权限,如下所述。
3) 设置对单独项目目录的访问权限:
假设您在默认位置 (/var/www/) 之外的另一个位置(如目录 /path/to/my/sample/mvc/)创建项目。然后,考虑到只有子文件夹 public 应该可以从外部访问,为它创建一个 Web 服务器配置,如下所示:
ServerName www.my-sample-mvc.com
DocumentRoot "/path/to/my/sample/mvc/public"
<Directory "/path/to/my/sample/mvc/public">
Require all granted
# When Options is set to "off", then the RewriteRule directive is forbidden!
Options FollowSymLinks
# Activate rewriting engine.
RewriteEngine On
# Allow pin-pointing to index.php using RewriteRule.
RewriteBase /
# Rewrite url only if no physical folder name is given in url.
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite url only if no physical file name is given in url.
RewriteCond %{REQUEST_FILENAME} !-f
# Parse the request through index.php.
RewriteRule ^(.*)$ index.php [QSA,L]
</Directory>
请注意,上述设置可以定义为:
- 在 Apache 的配置文件中,或者
- 在项目内的 .htaccess 文件中,或
- 在虚拟主机定义文件中。
如果使用虚拟主机定义文件,设置必须包含在标签<VirtualHost>和</VirtualHost>之间:
<VirtualHost *:80>
... here come the settings ...
</VirtualHost>
注意:不要忘记在每次更改配置设置后重新启动网络服务器。
一些资源: