在 Web 服务器中隐藏 PHP 入口文件(如 index.php
)是一种常见的做法,可以使 URL 更加简洁和友好。以下是针对不同 Web 服务器的配置方法:
Apache 是最常用的 Web 服务器之一,可以通过 .htaccess
文件或 Apache 配置文件来实现 URL 重写,从而隐藏 PHP 入口文件。
.htaccess
文件确保 Apache 的 mod_rewrite
模块已启用。可以通过以下命令检查:
sudo a2enmod rewrite
sudo systemctl restart apache2
在项目的根目录下创建或编辑 .htaccess
文件,添加以下内容:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
这段配置的作用是:
RewriteEngine On
:启用重写引擎。RewriteCond %{REQUEST_FILENAME} !-f
:如果请求的文件不存在。RewriteCond %{REQUEST_FILENAME} !-d
:如果请求的目录不存在。RewriteRule ^(.*)$ index.php/$1 [L,QSA]
:将所有请求重写到 index.php
,并保留查询字符串。确保 Apache 配置允许 .htaccess
文件覆盖配置。在 Apache 配置文件(如 000-default.conf
或 apache2.conf
)中,确保以下配置:
<Directory /var/www/html>
AllowOverride All
</Directory>
重启 Apache 服务器:
sudo systemctl restart apache2
如果你不想使用 .htaccess
文件,可以直接在 Apache 的配置文件中添加重写规则:
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</Directory>
Nginx 是另一个流行的 Web 服务器,通常用于高性能的 Web 应用。Nginx 的配置与 Apache 有所不同。
编辑 Nginx 的配置文件(通常位于 /etc/nginx/sites-available/default
或 /etc/nginx/conf.d/default.conf
),找到 server
块,并添加以下内容:
server {
listen 80;
server_name yourdomain.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的 PHP 版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
这段配置的作用是:
try_files $uri $uri/ /index.php?$query_string;
:尝试匹配请求的文件或目录,如果不存在,则将请求重写到 index.php
,并保留查询字符串。location ~ \.php$
:处理 PHP 文件的请求。测试 Nginx 配置是否正确:
sudo nginx -t
重启 Nginx 服务器:
sudo systemctl restart nginx
如果你使用的是 IIS(Internet Information Services),可以通过 URL 重写模块来实现隐藏 PHP 入口文件。
确保已安装 URL 重写模块。如果没有安装,可以从 IIS URL 重写模块 下载并安装。
在 IIS 管理器中,选择你的网站,然后双击 "URL 重写"。
点击 "添加规则",选择 "空白规则"。
配置规则:
^(.*)$
{REQUEST_FILENAME}
index.php/{R:1}
保存规则并重启 IIS。
Lighttpd 是一个轻量级的 Web 服务器,配置方式如下:
编辑 Lighttpd 的配置文件(通常位于 /etc/lighttpd/lighttpd.conf
),添加以下内容:
url.rewrite-if-not-file = (
"^/(.*)$" => "/index.php/$1"
)
重启 Lighttpd 服务器:
sudo systemctl restart lighttpd
通过配置 Web 服务器的 URL 重写规则,可以隐藏 PHP 入口文件,使 URL 更加简洁和友好。不同的 Web 服务器(如 Apache、Nginx、IIS、Lighttpd)有不同的配置方式,但核心思想都是将请求重写到 index.php
文件。