本文目录导读:

在 PHP 中隐藏入口文件(通常是 index.php)主要使用 Web 服务器配置来实现 URL 重写,以下是常见的方法:
Apache 服务器
使用 .htaccess 文件
在项目根目录创建 .htaccess 文件:
<IfModule mod_rewrite.c>
RewriteEngine On
# 如果请求的文件或目录不存在
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 将所有请求重定向到 index.php
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
或者在 Apache 虚拟主机配置中:
<VirtualHost *:80>
DocumentRoot "/var/www/html"
ServerName example.com
<Directory "/var/www/html">
AllowOverride All
Require all granted
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
</Directory>
</VirtualHost>
Nginx 服务器
在 Nginx 配置文件中添加:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php;
location / {
# 如果文件或目录不存在
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?$1 last;
break;
}
}
# 或者更好的方式(推荐)
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
PHP 内置服务器
对于开发环境,可以使用 PHP 内置服务器并配合路由规则:
# 启动 PHP 服务器 php -S localhost:8000 router.php
创建 router.php 文件:
<?php
// router.php - PHP 内置服务器路由器
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// 检查文件是否存在
if ($path !== '/' && file_exists(__DIR__ . $path)) {
return false; // 让内置服务器直接服务静态文件
}
// 否则加载 index.php
require_once __DIR__ . '/index.php';
使用框架方式(如 Laravel)
现代 PHP 框架通常自带路由系统:
// Laravel public/index.php require __DIR__.'/../vendor/autoload.php'; $app = require_once __DIR__.'/../bootstrap/app.php'; $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class); $response = $kernel->handle($request = Illuminate\Http\Request::capture()); $response->send(); $kernel->terminate($request, $response);
URL 重写示例效果
重写前后对比:
# 重写前
http://example.com/index.php/product/123
# 重写后
http://example.com/product/123
注意事项
排除静态资源
确保静态文件(图片、CSS、JS)不被重写:
# Apache - 排除特定目录
RewriteCond %{REQUEST_URI} !^/assets/
RewriteCond %{REQUEST_URI} !^/uploads/
Nginx 静态文件处理
location ~* \.(jpg|jpeg|png|gif|css|js)$ {
expires 30d;
access_log off;
}
安全建议
-
项目目录结构:
project/ ├── public/ # 公共可访问目录 │ ├── index.php │ └── assets/ ├── app/ # 应用代码(禁止直接访问) ├── config/ └── vendor/ -
目录访问控制: 在
/app、/config等敏感目录放入.htaccess:# .htaccess Deny from all
选择哪种方法取决于你的服务器环境,Apache 最常用 .htaccess,Nginx 则需要修改配置文件,如果需要更详细的配置,请告诉我你的具体服务器环境。